I am working on xamarin.form cross-platform application , i want to navigate from one page to another on button click. As i cannot do Navigation.PushAsync(new Page2());
One way is you can pass the Navigation through the VM Constructor. Since pages inherit from VisualElement
, they directly inherit the Navigation
property.
Code behind file:
public class SignIn : ContentPage
{
public SignIn(){
InitializeComponent();
// Note the VM constructor takes now a INavigation parameter
BindingContext = new LocalAccountViewModel(Navigation);
}
}
Then in your VM, add a INavigation
property and change the constructor to accept a INavigation
. You can then use this property for 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 an issue with your code that you should fix: The GoToPage2()
method must be set async
and return the Task
type. In addition, the command will perform an asynchronous action call. This is because you must do page navigation asychronously!
Hope it helps!