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:
- How to set your initial page in app.xaml
- 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
Edit your App.xaml.cs file - See the project online
Create a Xaml view based on a ContentPage. Name it [something]View.xaml
Create a ViewModel inheriting from ViewModelBase and Name it [something]ViewModel.cs - yes naming conventions are important. Resolving views depends on it.
- 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>
Register the views in the ViewModelLocator.ViewModelLocator() in the services directory. E.g.
Add "navigate to" code to the appropriate ViewModels.