Can I add extra information to NSPopUpButton items in Xamarin.Mac?

101 Views Asked by At

I'm building a Mac OS app in C# using Xamarin.Mac. I'd like to populate a dropdown (NSPopUpButton) with items that store more information than just their title and index. Specifically I'd like to have each item also hold its own database ID, so when the user chooses that item from the dropdown I can easily fetch the relevant record from the database.

I see that NSPopUpButton uses instances of NSMenuItem, and it's easy enough to subclass NSMenuItem, but there doesn't seem to be a way to insert an instance directly. The AddItem() method only accepts a string (the title of the item) and has no overloads. Is there a way to use custom items, or am I stuck with just title and index to differentiate?

Thanks!

1

There are 1 best solutions below

1
On BEST ANSWER

Add your subclass'd NSMenuItem via the NSPopUpButton.Menu.AddItem method.

Example NSMenuItem:

public class MyNSMenuItem : NSMenuItem
{
    public string SomeCustomProperty { get; set; }
    
    ~~~~
    // add all the .ctors w/ base calls....
}

Example usage:

var popUpButton = new NSPopUpButton()
{
    Frame = new CGRect(100, 100, 100, 100),
    Title = "A pop button",
};
var menuItem = new MyNSMenuItem()
{
    Title = "StackOverflow",
    SomeCustomProperty = "SomeInstance",
};
menuItem.Activated += (sender, e) =>
{
    Console.WriteLine((sender as MyNSMenuItem).SomeCustomProperty);
};
popUpButton.Menu.AddItem(menuItem);
this.View.AddSubview(popUpButton);