Implementing Navigation Services in MVVM for Xamarin

This technique uses ViewModel first navigation which makes all the sense in the world if you are using MVVM. Otherwise, not so much. See: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/enterprise-application-patterns/ for more details.

First, take a look at the attached project. It is a bare minimum implementation that shows:

  1. How to set your initial page in app.xaml
  2. How to implement the Navigation services and base classes.

What you want to know is how to add additional pages. The next section walks you through that process.

Steps

  1. Edit your App.xaml.cs file - See the project online

  2. Create a Xaml view based on a ContentPage. Name it [something]View.xaml

  3. Create a ViewModel inheriting from ViewModelBase and Name it [something]ViewModel.cs - yes naming conventions are important. Resolving views depends on it.

  4. Make sure that the the binding context is setup correctly see the example below:
       1 <?xml version="1.0" encoding="utf-8" ?>
       2 <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
       3              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
       4              xmlns:local="clr-namespace:DeleteMe"
       5              x:Class="DeleteMe.Views.TwoView"
       6              xmlns:my="clr-namespace:DeleteMe.ViewModels">
       7   <ContentPage.BindingContext>
       8     <my:TwoViewModel />
       9   </ContentPage.BindingContext>
      10   <StackLayout>
      11     <Label Text="Welcome to page two - use the back button to navigate back to the main page."
      12         VerticalOptions="CenterAndExpand"
      13         HorizontalOptions="CenterAndExpand" />
      14         <Button Text="Navigate back to home" Command="{Binding ButtonCommand}" />
      15     </StackLayout>
      16 </ContentPage>
    
  5. Register the views in the ViewModelLocator.ViewModelLocator() in the services directory. E.g.

       1 static ViewModelLocator()
       2 {
       3     _container = new TinyIoCContainer();
       4     _container.Register<MainPageViewModel>();
       5     ...
       6 }
    
  6. Add "navigate to" code to the appropriate ViewModels.

ProgrammingLinks/AndroidDevelopment/ImplementingNavigationServicesInMvvm (last edited 2019-07-22 00:50:52 by scot)