wp7appdevelopment

Adventures in Windows Phone app development

Monthly Archives: September 2012

NavigationService – passing parameters

When developing apps for the Windows Phone, the NavigationService is used to navigate from one page in your app to another. The simplest way to navigate to a new page is with a call to NavigationService.Navigate(Uri). For example, to navigate to a new page when a button is clicked:

private void button_click(Object sender, RoutedEventArgs e)
{
    NavigationService.Navigate(new Uri ("/Page2.xaml", Uri.Relative) );
}

But what if you want to pass a piece of information from page 1 to page 2. You could create a global variable, and store the information before navigating and then retrieve it from the new page. But often it’s easier to just pass a simple piece of data through the Navigate() call.

Code on Page 1 — Passing the data

private void button_click(Object sender, RoutedEventArgs e)
{
    NavigationService.Navigate(new Uri ("/Page2.xaml?msg="my_string", Uri.Relative) );
}

Code on Page 2– Retrieving the data

protected override void onNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    base.onNavigatedTo(e);
    string msg;
    if(NavigationContext.QueryString.TryGetValue(“msg”,out msg))
    {
       // use the passed value as appropriate. For example:
      this.TextBox1.Text = msg;
    }
}

Passing Multiple Parameters

Note: You can pass more than one piece of information using the “&” character in your query string. For example:

NavigationService.Navigate(new Uri ("/Page2.xaml?firstName="Joe"&lastName="User", Uri.Relative) );

Additional resources

See the following posts for more information: