How to bind Toolbar MenuItem.IsEnabled with MvvmCross and Xamarin.Android -
using mvvmcross , xamarin.android possible bind isenabled property of toolbar menuitem boolean value in viewmodel? if so, how done?
i believe it's impossible @ time bind android imenuitem.isenabled boolean value on viewmodel due fact isenabled readonly , changed enabled state of menu item requires call setisenabled(bool)
.
i worked around limitation adding event handler mvxviewmodel.propertychanged
in activity/fragment. viewmodels inherit mvxviewmodel
i'll share a way can accomplished. of app implemented fragments, example reflects that, (in actual code i've put of in base fragment class, wanted keep simple):
public class myviewmodel : mvxviewmodel { public bool menuitemisenabled { get{return _menuitemisenabled;} set{setproperty(ref _menuitemisenabled, value); } } [mvxfragment(typeof(mainviewmodel), resource.id.content_frame, true)] [register(nameof(myfragment))] public class myfragment : mvxfragment { private toolbar toolbar; //menuitem enabled state should change viewmodel property private imenuitem mymenuitem; public new myviewmodel viewmodel { { return (myviewmodel)base.viewmodel; } set { base.viewmodel = value; } } public override view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { var view = base.oncreateview(inflater, container, savedinstancestate); //we'll need toolbar later when set isenabled "binding" toolbar = view.findviewbyid<toolbar>(resource.id.toolbar); return view; } public override void onviewmodelset() { base.onviewmodelset(); viewmodel.propertychanged += viewmodel_propertychanged; } public override void oncreateoptionsmenu(imenu menu, menuinflater inflater) { base.oncreateoptionsmenu(menu, inflater); //create menu based on menu resource inflater.inflate(resource.menu.my_menu, menu); //save reference menu item can update when viewmodel changes mymenuitem = menu.finditem(resource.id.my_menu_item); //set initial enabled state based on viewmodel mymenuitem.setenabled(viewmodel.menuitemisenabled); } private void viewmodel_propertychanged(object sender, system.componentmodel.propertychangedeventargs e) { //when viewmodel.menuitemisenabled updated, update menuitem enabled state if (e.propertyname == nameof(viewmodel.menuitemisenabled )) bincontentsmenuitem?.setenabled(viewmodel.menuitemisenabled); } }
this should considered pseudocode, since it's trying demonstrate general concepts used work around original problem.
Comments
Post a Comment