Pap
Pap

Reputation: 148

MVVMCross+Android: DataBinding Context Menu options on ViewModel properties?

How can I Databind my menu options properties(eg the Enabled Property) to a ViewModel property?

My menu is created within my MvxActivity-inherited class as follows:

public override void OnCreateContextMenu( IContextMenu menu, View v, IContextMenuContextMenuInfo info )
{
        switch (v.Id)
        {
            case Resource.Id.textView1:
                menu.Add( 0, 0, 0, "Menu Option1" );
                menu.Add( 0, 1, 0, "Menu Option2" );

                break;
            case Resource.Id.textView2:
                menu.Add( 0, 2, 0, "Menu Option3" );
                menu.Add( 0, 3, 0, "Menu Option4" );

                break;
        ...
        }
        ...
}

I know that I can enable/disable individual Menu Items as follows:

IMenuItem menuOption = menu.FindItem( 1 ); // Refers to "Menu Option2" above

if (menuOption != null)
{
    menuOption.SetEnabled(false);
}

But how can I achieve this using MVVMCross binding? I suppose I could do this in C#(dynamically) but I'm not sure how to do this. Can anybody show me please?

Thanks In Advance.

Upvotes: 1

Views: 2250

Answers (1)

Stuart
Stuart

Reputation: 66882

Since Menu's are created "on demand" then I generally handle this by just implementing SetEnabled type things using ViewModel current properties.

e.g.

  var myViewModel = (MyViewModel)ViewModel;
  var menuOption = menu.FindItem( 1 ); // Refers to "Menu Option2" above
  menuOption.SetEnabled(myViewModel.CanDoSomething);

Cleverer - more "binding" options are available - e.g. we could create a menu-wrapping object to hook things up automatically - but in the few cases where I use menus, then I find this ViewModel approach works OK

Upvotes: 3

Related Questions