Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 769
sohum Avatar asked Oct 27 '11 21:10

sohum


1 Answers

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.

like image 163
sohum Avatar answered Sep 30 '22 13:09

sohum