Mvvmlight - What is the “Right Way” for Defining URL Parameters for a View Model

I just switch the project to mvvmlight and try to do something "right"

I have a simple list app

When an item is selected in the list, I connected RelayCommand

This RelayCommand calls the INavigationService service (http://geekswithblogs.net/lbugnion/archive/2011/01/06/navigation-in-a-wp7-application-with-mvvm -light.aspx), which moves to the URL e.g. "/DetailPage.xaml?DetailId=12"

Then DetailPage.xaml is loaded and ... that's where I'm a little unsure ...

  • How should a DetailPage connect to a DetailView with a DetailId of 12?
  • Should I do this in Xaml somehow using a property in the ViewLocator?
  • Should I do this in the NavigatedTo method?

Please feel free to tell me the full sample - sure that it was done (a hundred) thousand times earlier, but all blogs and tutorials seem to skip this last little thing (focusing instead on messaging and on ioc on on navigationservice)

Thanks!

+4
source share
2 answers

The only place you can find the URL parameter is in the view. Since your opinion probably depends on it, you should get it in the OnNavigatedTo method.

Then you must pass it along with your view model, using messaging (dear, if you ask me), or by contacting your datacontext (which I assume is the view model), and the execeuting method for this.

private AddTilePageViewModel ViewModel { get { return DataContext as AddTilePageViewModel; } } protected override void OnNavigatedTo(NavigationEventArgs e) { var postalCode = NavigationContext.TryGetKey("PostalCode"); var country = NavigationContext.TryGetStringKey("Country"); if (postalCode.HasValue && string.IsNullOrEmpty(country) == false) { ViewModel.LoadCity(postalCode.Value, country); } base.OnNavigatedTo(e); } 

I use some special extensions for the NavigationContext to simplify it.

 namespace System.Windows.Navigation { public static class NavigationExtensions { public static int? TryGetKey(this NavigationContext source, string key) { if (source.QueryString.ContainsKey(key)) { string value = source.QueryString[key]; int result = 0; if (int.TryParse(value, out result)) { return result; } } return null; } public static string TryGetStringKey(this NavigationContext source, string key) { if (source.QueryString.ContainsKey(key)) { return source.QueryString[key]; } return null; } } } 
+5
source

Create a new WindowsPhoneDataBound application, it has an example of how to handle navigation between views. Basically you process the navigation part in your view, and then set the DataContext view to the query string. I think this works well with the MVVM pattern, since your ViewModels don't have to know anything about navigation (which IMO should be handled at the user interface level).

0
source

All Articles