1

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!

Nat Webb
  • 669
  • 1
  • 7
  • 18
  • What is the problem with subclassing it and adding a property to hold your extra info? – SushiHangover Dec 18 '20 at 17:12
  • I can't figure out how to add an instance of that subclass to the NSPopUpButton's items. The only AddItem method I see only takes a string (for the Title property) and the item it creates is a standard NSMenuItem. – Nat Webb Dec 19 '20 at 02:33
  • 1
    You need to use the `NSPopUpButton.Menu` property, see my answer. – SushiHangover Dec 19 '20 at 23:47

1 Answers1

3

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);
SushiHangover
  • 73,120
  • 10
  • 106
  • 165