NavigationService with MVVM Light and Template 10

2015-10-08 13:16:03来源:作者:人点击

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 theNavigationService this toolkit provides.

Template 10 too comes with its own NavigationService. It is accessible from the Application BootStrapperclass 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 PageKeysdictionary exposed by BootStrapper. We can do this in the OnInitializeAsyncmethod:

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.Navigatemethod 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 sampleof this approach in the official Template 10 GitHub repository (thanks to Jerry Nixonfor accepting my pull request!). As said, this is strongly recommended when we use the MVVM pattern.