2

I develop an universal app Windows 8.1/ Windows Phone 8.1 with MVVMLight. I would like to know which is the best practice to implement navigation between the pages.
There is the following pages:

  • MainPage: is a login page
  • HomePage: is a hub with different sections "list of themes", "list of contacts", "user details"
  • ListArticlesFromTheme : list of articles for the selected theme
  • DetailsContact : details of the selected contact
  • DetailsArticle : details of the selected article

I need so to pass parameters by navigating from a page to another: the selected theme, the selected contact, the selected article, ...

I found an example implementation of navigation tavers MVVMLight v5, but without parameters: navigationservice-in-mvvm-light-v5
I found another example with the parameters, but I haven't managed to implement it:
navigating-to-a-new-page-from-the-view-model-in-windows-phone-8-1-universal-app

  • Is it better to manage navigation through the Views or the ViewModels?
  • Do you have a more detailed example showing navigation with parameters?
Community
  • 1
  • 1
Gold.strike
  • 1,269
  • 13
  • 47

1 Answers1

1

If you want to either:

  • Access the parameter that is passed in the NavigationServicesEx.Navigate method

  • Call a method in your ViewModel when a page is navigated to.

This blog by Marco Minerva shows how to hook in to the Frame_Navigating event that it missing from the vanilla NavigationServiceEx class.

Create the INavigable interface described in the blog:

public interface INavigable
{
    Task OnNavigatedToAsync(object parameter, NavigationMode mode);
    void OnNavigatingFrom(NavigatingCancelEventArgs e);
    void OnNavigatedFrom();
}

Add a handler for the Frame.Navigating event in the NavigationServicesEx class (with some additional plumbing, see blog) then realise the INavigable interface in your ViewModels.

You will then be able to access the parameter that you passed in your Navigate call:

NavigationServiceEx.Navigate(typeof(DestinationPage).FullName, yourParameter);

In the OnNavigatedToAsync method that you implement in your ViewModel:

public Task OnNavigatedToAsync(object parameter, NavigationMode mode)
{
    if (parameter != null)
    {
        YourThing thing = parameter as YourThing;
        this.UseYourThing(thing);
    }
    return Task.CompletedTask;
}

EDIT: Oh, and navigate through the ViewModel. You can call a method in your VM that handles navigation from either a Command or in the View's code behind.

Tim Tyler
  • 2,380
  • 2
  • 16
  • 13