Page Navigation using MVVM in Xamarin.Forms

Waleed Arshad picture Waleed Arshad · Apr 6, 2017 · Viewed 32k times · Source

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()); in ViewModel because it only possible in Code-Behid file. please suggest any way to do this?

Here is my 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}" />    
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Here is my 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));
    }
}

Answer

TaiT&#39;s picture TaiT's · Apr 6, 2017

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!