Creating NSMenuItems programmatically in MonoMac

I am trying to programmatically add a menu to my MonoMac application. I opened MainMenu.xib and removed all NSMenuItem from the MainMenu element.

I add the following code to the 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 does nothing.

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

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

+6
source share
1 answer

Turns out I needed to do the following:

 fileMenuItem.Submenu = fileMenu; 

The NSMenuItem submenu property must be set to the actual menu instead of the menu property.

+5
source

Source: https://habr.com/ru/post/900245/


All Articles