2

So I'm creating UWP app, and using method

Frame.Navigate(Type type)

to navigate through my views. But one of my pages requires passing an object with navigation, so i use this method

Frame.Navigate(Type type, object param)

and then I can get the parameter in the code-behind of page like this:

public object NavigationParameter { get; private set; }

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    NavigationParameter = e.Parameter;
}

That's great, but I'm using MVVM pattern, so I want to get this parameter on the VM of my page. How can I do that?

P.S.: Solution with zero code behind would be spectacular.

2 Answers2

1

I would recommend you take a look at some MVVM framework that handle stuff like this for you and allow you to achieve your honorable no code behind goal. I use and recommend Caliburn.Micro because it contains everything you need (navigation service, automatic view-viewmodel binding etc.).

Igor Kulman
  • 16,211
  • 10
  • 57
  • 118
  • Well company I'm gonna be working for uses only MVVMLight, which, as well as i know, doesn't contain such things. But thanks for reply anyway. –  Oct 20 '16 at 17:48
  • @Денис Селюков If you are using MVVM Light you can use the Messenger to Pass Values Between View Models . Check the http://stackoverflow.com/questions/18087906/use-mvvm-lights-messenger-to-pass-values-between-view-model/18087982#18087982 – Joel Joseph Oct 21 '16 at 09:39
1

If you are using UWP with MVVM Light and 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 advises how to hook in to the Frame_Navigating event (that it missing from the vanilla NavigationServiceEx class) to access the argument when the destination page is navigated to.

tl;dr

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;
}
Tim Tyler
  • 2,380
  • 2
  • 16
  • 13