How to manage the state of the menu items ?

pierreDurantpierreDurant pierre DurantUSMember ✭✭
edited April 29 in Xamarin.Mac

I want to manage the state of a menu item
Let’s take the example “macmenu” provided by Xamarin

In app delegate.cs, the method:

    partial void phrasesDate (Foundation.NSObject sender) {
            
        if (textEditor == null) return;
            
    textEditor.Text += DateTime.Now.ToString("D");


I want to add
Sender.State = NSCellStateValue.On;


But of course this doesn’t work as “sender” is an NSObject and not an NSMenuItem.

So I modify the method to

partial void phrasesDate (NSMenuItem sender) {


But in this cas, I also have to modify the appdelegate.designer.cs.
[Action ("phrasesDate:")]

partial void phrasesDate (Foundation.NSObject sender);

To
[Action ("phrasesDate:")]

partial void phrasesDate (NSMenuItem sender);

Question: is there no other way to do this ?
Because, it’s not recommended to modify the “appdelegate.designer.cs”…

Thanks

Pit

Answers

  • XavierFortinXavierFortin Xavier Fortin USMember ✭✭

    That does seem a bit convoluted.

    Why not just cast your sender NSObject to NSMenuItem?

    NSMenuItem menuItem = (NSMenuItem)sender;
    
  • pierreDurantpierreDurant pierre Durant USMember ✭✭

    Hi Xavier,

    Indeed, it's a good solution !
    I don't know if it's the "standard way" to do that, but it works !

    thanks !

    If someone has a better idea ?

    Pit

  • SocratSocrat Yuri Kuznetsov USMember ✭✭

    you can bind every menu item, in Xcode NSMenuItem have property - Enabled, read this
    https://developer.xamarin.com/guides/mac/application_fundamentals/databinding/
    or you can do like in this article
    https://developer.xamarin.com/guides/mac/user-interface/working-with-menus/

  • JGoldbergerJGoldberger Jon Goldberger USXamarin Team, University Xamurai

    @pierreDurant said:
    Hi Xavier,

    Indeed, it's a good solution !
    I don't know if it's the "standard way" to do that, but it works !

    Yes, that is the standard way. Since the sender can be different specific types, the parameter's type is the broad NSObject which virtually every Mac or iOS object inherits from. So in any situation where you are getting an NSObject as a parameter, you will have to cast that NSObject to the specific type the object really is in order to access that specific objects methods and properties.

  • pierreDurantpierreDurant pierre Durant USMember ✭✭

    thanks !

Sign In or Register to comment.