MvvmLight navigation in Xamarin.Forms

MvvmLight is a very popular Mvvm framework created by Laurent Bugnion. I like to use MvvmLight but when developing mobile apps I miss the possibility to create modals, so I created an extension to the navigation service in MvvmLight, read more about it here.

We can also use MvvmLight when we developing apps with Xamarin.Forms but there are no navigation service implementation for it. Because of that I have added that to my MvvmLight Navigation Service Extension. The code and complete samples can be found on GitHub.

The first step to use it is to install the nuget package.

install-package MvvmLightNavigationServiceExtension.Forms

Next step is to configure the navigation service. This is pretty much the same as if we use MvvmLight in other project. The important part here is the Initialize method that require a Xamarin.Forms navigation object. We will get the navigation object from a NavigationPage that we create before we starting to configure MvvmLight. In this sample and the in the sample code on GitHub I will use Autofac as IoC container. All the code below should be in the constructor of the App class in your Xamarin.Forms project.

navigationPage = new NavigationPage();

var navigationService = new NavigationService();
navigationService.Initialize(navigationPage.Navigation);

navigationService.Configure("Main", typeof(MainView));
navigationService.Configure("About", typeof(AboutView));

var builder = new ContainerBuilder();
builder.RegisterInstance(navigationService);

var container = builder.Build();

ServiceLocator.SetLocatorProvider(() => new AutofacServiceLocator(container));

navigationPage.PushAsync(new MainView());

MainPage = navigationPage;

To use it in a ViewModel we need to resolve the INavigationService interface.

var navigation = ServiceLocator.Current.GetInstance();
navigation.NavigateTo("About");

We can also have a parameter with the NavigateTo method, but then the view we navigating to need to have a constructor with one parameter.

var navigation = ServiceLocator.Current.GetInstance();
navigation.NavigateTo("About", myParameter);
public MySecondView(object parameter)
{
     //Do something with the parameter.
}

If we want to use OpenModal method from the MvvmLight Navigation Extension we had to add a using to it.

using MvvmLightNavigationExtension;
var navigation = ServiceLocator.Current.GetInstance();
navigation.OpenModal("About");

If you have feedback, feel free to contact me.

  3/10/2016 - 8:51 PM