6

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?

Community
  • 1
  • 1
sohum
  • 3,207
  • 2
  • 39
  • 63

1 Answers1

5

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.

sohum
  • 3,207
  • 2
  • 39
  • 63
  • this works, though you should also set title of fileMenu.title = "Someting" if it is not first item (that always have name of application) – PetrV Aug 10 '15 at 12:41