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; } } }
source share