i have simple xamarin.forms.contentpage displays menu items in listview
:
<contentpage x:class="mob.views.public.menupage" ... > <scrollview> <listview itemssource="{binding menuitems}" itemtapped="{binding onmenuitemtapped}"> <listview.itemtemplate> <datatemplate> <textcell text="{binding key}" /> <!-- how pass "{binding value}" onmenuitemtapped? --> </datatemplate> </listview.itemtemplate> </listview> </scrollview> </contentpage>
code behind:
public class menupage : contentpage { public menupage() { initializecomponent(); bindingcontext = new menuviewmodel(); } private async void onmenuitemtapped(object sender, itemtappedeventargs e) { await (this.bindingcontext menuviewmodel).onmenuitemtappedasync(/* must pass value here*/); } }
as can see, itemssource
bound menuitems
property of viewmodel. property of type dictionnary<string, string>
. key
used display text of items while value
should passed parameter onmenuitemtapped
event.
class menuviewmodel : viewmodelbase { ... public idictionary<string, string> menuitems { { return _menuitems; } set { setproperty(ref _menuitems, value); } } // public icommand onmenuitemtappedcommand { get; set; } public menuviewmodel() { menuitems = new dictionary<string, string>(); menuitems.add("xxx", "pagex"); menuitems.add("yyy", "pagey"); menuitems.add("zzz", "pagez"); // ... // would've prefere bind item tap using command can't figure out how // onmenuitemtappedcommand = new command<string>(onmenuitemtappedasync); } public async task onmenuitemtappedasync(string targetpage) { // await navigation.pushmodalasync(...); // --> depending on targetpage } }
my goal navigate right page depending on value passed onmenuitemtappedasync
.
note, trying "pure" mvvm here. meaning know should not use events , leave code behind empty. can't figure out how use commands in context.
any idea/advice how achieve this?
add tapgesture viewcell content , bind command it. ex:
<tapgesturerecognizer command="{binding onmenuitemtappedcommand}" commandparameter="{binding .}" />
in case can bind command directly textcell.
<textcell command="{binding onmenuitemtappedcommand}" commandparameter="{binding .}">
Comments
Post a Comment