c# - Xamarin.form Page Navigation in mvvm -
i working on xamarin.form cross-platform application , want navigate 1 page on button click. cannot navigation.pushasync(new page2()); in viewmodel because possible in code-behid file. please suggest way this?
here view:
<?xml version="1.0" encoding="utf-8" ?> <contentpage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:class="calculator.views.signin" xmlns:viewmodels="clr-namespace:calculator.viewmodels;assembly=calculator"> <contentpage.bindingcontext> <viewmodels:localaccountviewmodel/> </contentpage.bindingcontext> <contentpage.content> <stacklayout> <button command="{binding continuebtnclicked}"></button> </stacklayout> </contentpage.content> </contentpage> here viewmodel:
public class localaccountviewmodel : inotifypropertychanged { public localaccountviewmodel() { this.continuebtnclicked = new command(gotopage2); } public void gotopage2() { ///// } public icommand continuebtnclicked { protected set; get; } public event propertychangedeventhandler propertychanged; protected virtual void onpropertychanges([callermembername] string propertyname = null) { propertychanged?.invoke(this, new propertychangedeventargs(propertyname)); } }
one way can pass navigation through vm constructor. since pages inherit visualelement, directly inherit navigation property.
code behind file:
public class signin : contentpage { public signin(){ initializecomponent(); // note vm constructor takes inavigation parameter bindingcontext = new localaccountviewmodel(navigation); } } then in vm, add inavigation property , change constructor accept inavigation. can use property navigation:
public class localaccountviewmodel : inotifypropertychanged { public inavigation navigation { get; set;} public localaccountviewmodel(inavigation navigation) { this.navigation = navigation; this.continuebtnclicked = new command(async () => await gotopage2()); } public async task gotopage2() { ///// await navigation.pushasync(new page2()); } ... note issue code should fix: gotopage2() method must set async , return task type. in addition, command perform asynchronous action call. because must page navigation asychronously!
hope helps!
Comments
Post a Comment