Home > C#, MVVM, Universal Windows Platform > NavigationService with MVVM Light and Template 10

NavigationService with MVVM Light and Template 10

07/10/2015

Navigation is one of the most important part of every Universal Windows app. If you are accustomed to use MVVM Light, probably you already leverage the NavigationService this toolkit provides.

Template 10 too comes with its own NavigationService. It is accessible from the Application BootStrapper class and directly from classes inheriting from ViewModelBase.

First versions of Template 10 allowed to navigate by page type, which is the standard on the XAML Frame. If, however, we are following the MVVM pattern, and so we control navigation from view models, this approach isn’t correct, because view models shouldn’t know anything about pages. In fact, NavigationService from MVVM Light requires to associate each page type to a key and then use it to handle navigation from views models (as described in the article Navigation Service in MVVM Light 5).

Last version of Template 10 (1.0.4 on NuGet) improves its NavigationService by providing a similar approach based on keys, in order to isolate view types from view models. Let’s see how to use it.

The first step is creating a custom Enum that represents the pages of our app:

public enum Pages
{
    MainPage,
    DetailsPage,
    OtherPage,
    //...
}

Then, we need to populate the PageKeys dictionary exposed by BootStrapper. We can do this in the OnInitializeAsync method:

public override Task OnInitializeAsync(IActivatedEventArgs args)
{
    var keys = PageKeys<Pages>();
    keys.Add(Pages.MainPage, typeof(MainPage));
    keys.Add(Pages.DetailsPage, typeof(DetailsPage));

    return base.OnInitializeAsync(args);
}

We’re associating each page type with the corresponding enum value (lines 4-5). In this way, we can use an overload of the NavigationService.Navigate method that takes as first argument the enum value corresponding to the page type we want to navigate to (instead of use the page type directly). For example:

NavigationService.Navigate(Pages.MainPage);

// Navigation with parameters.
NavigationService.Navigate(Pages.DetailsPage, "parameters");

You can find a sample of this approach in the official Template 10 GitHub repository (thanks to Jerry Nixon for accepting my pull request!). As said, this is strongly recommended when we use the MVVM pattern.

  1. No comments yet.
  1. 07/10/2015 at 12:46
Comments are closed.
%d bloggers like this: