sohum
sohum

Reputation: 3227

Creating NSMenuItems programmatically in MonoMac

I'm trying to programmatically add a menu to my MonoMac application. I've opened up the MainMenu.xib and removed all NSMenuItem from the MainMenu control.

I'm adding the following code into my FinishedLaunching override:

var fileMenuItem = new NSMenuItem("File");
var fileMenu = new NSMenu();

var fileNew = new NSMenuItem("New");
var fileOpen = new NSMenuItem("Open");
var fileSave = new NSMenuItem("Save");

fileMenu.AddItem(fileNew);
fileMenu.AddItem(fileOpen);
fileMenu.AddItem(fileSave);

fileMenuItem.Menu = fileMenu;

NSApplication.SharedApplication.MainMenu.AddItem(fileMenuItem); 

But it's not doing anything.

When I add the code to MainWindowController.Initialize(), I get an assertion failure "item to be inserted into menu already is in another menu"

I was porting the code found in this SO answer: Creating NSMenu with NSMenuItems in it, programmatically?

Upvotes: 6

Views: 1358

Answers (1)

sohum
sohum

Reputation: 3227

Turns out I had to do the following:

fileMenuItem.Submenu = fileMenu;

The Submenu property of the NSMenuItem should have been set to the actual menu instead of the Menu property.

Upvotes: 5

Related Questions