Passing values to Windows Phone 7 pages: URI paremeters and QueryString
Join the DZone community and get the full member experience.
Join For FreeFrom my point of view specifying parameters and their values in URI (QueryString) is probably the easiest way to pass data from one page to another during the Navigation. In this post I am going to cover this approach for passing values to pages and in future posts I am going to explain few other ways.
Passing values
To pass parameters and values from one page to another you need to initialize an URI with parameters and their values. To do so add question mark (“?”) to the end and then specify parameter=value pair(check code bellow). Use Uri.EscapeUriString to avoid format exceptions during the navigation.
NavigationService.Navigate( new Uri("/DestinationPage.xaml?parameter1=v1", UriKind.Relative) ); // OR NavigationService.Navigate( new Uri(string.Format("/DestinationPage.xaml?parameter1={0}" , Uri.EscapeUriString(stringParameterValue), UriKind.Relative)));
To specify multiple parameters use “&” character.
NavigationService.Navigate( new Uri("/DestinationPage.xaml?parameter1=v1¶meter2=v2", UriKind.Relative) );
Getting/Parsing values
After passing values to destination page you can get them using NavigationContext and QueryString. Usually, I implement this process within OnNavigatedTo method. You can get only string objects from QueryString meaning that if you have passed an integer as value the you have to parse value-string to integer type back.
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { string myParameterValue = NavigationContext.QueryString["parameter1"]; base.OnNavigatedTo(e); }
Limitation
In most of the cases absolute URI(with parameters/values) should not be very long. Try keeping the length lower than 2050 characters(not very accurate) otherwise you can get the following exception: System.ArgumentException: ShellPage URI too long
Advantages/Disadvantages
Advantages
- Safest way for Back button navigation. After user clicks on a back button he will be navigated to a previous page having preset parameters with values.
- Safest way for Tombstoning events. After application recovers from suspend mode active page has preset parameters with values.
Disadvantages
- Parsing QueryString parameter values. For example if you pass an integer value to another page then you have to get a string value from QueryString and parse it to integer again because you can only use string type for URI.
Source: http://www.eugenedotnet.com/2011/03/passing-values-to-windows-phone-7-pages-uri-paremeters-or-querystring/
Opinions expressed by DZone contributors are their own.
Comments