How to navigate to page with ICommand the right way

I want to navigate to page, when user click on a button it fires OpenPageCommand but I can't navigate to view from ViewModel because it violates MVVM so what's the right way to do it?

HomePage.xaml

...
<Button ...
        Text="Login"
        Command="{Binding OpenPageCommand}"
        CommandParameter="Login"/>

<Button ...
        Text="SignUp"
        Command="{Binding OpenPageCommand}"
        CommandParameter="SignUp"/>

<Button ...
        Text="Appointments"
        Command="{Binding OpenPageCommand}"
        CommandParameter="Appointments"/>

<Button ...
        Command="{Binding OpenPageCommand}"
        CommandParameter="FAQs"/>

<Button ...
        Text="New Appointment"
        Command="{Binding OpenPageCommand}"
        CommandParameter="NewAppointment"/>
...

HomeViewModel.cs

public ICommand OpenPageCommand { get; set; }

public HomeViewModel()
{
    OpenPage = new Command<string>((arg) => OpenPage(arg));
}

private async void OpenPage(string value)
{
    switch (value)
    {
        case "Login":
            await Application.Current.MainPage.Navigation.PushAsync(new LoginPage());
            break;
        case "SignUp":
            await Application.Current.MainPage.Navigation.PushAsync(new SignUpPage());
            break;
        case "Appointments":
            await Application.Current.MainPage.Navigation.PushAsync(new AppointmentsPage());
            break;
        case "FAQs":
            await Application.Current.MainPage.Navigation.PushAsync(new FaqPage());
            break;
        case "NewAppointment":
            await Application.Current.MainPage.Navigation.PushAsync(new NewAppointmentPage());
            break;
        default:
            return;
    }
}

Best Answers

Answers

  • AndreiMisiukevich_AndreiMisiukevich_ USMember ✭✭✭✭✭

    Create NavigationService, for example and call it with any DI container ;)

Sign In or Register to comment.