Homam
Homam

Reputation: 23841

How to pass a parameter to another WPF page

How to pass a parameter to another page and read it in WPF? I read on the internet that this could be done using the URL as the following:

NavigationService n = NavigationService.GetNavigationService(this);
n.Navigate(new Uri("Test.xaml?param=true", UriKind.Relative));

But I'm not able to read the parameter value in the Test.xaml page.

I cannot instantiate a new instance from the page and pass it by the constructor because I had a problem before the round-trip was to navigate using the page path.

Upvotes: 1

Views: 9008

Answers (2)

Jehof
Jehof

Reputation: 35544

You can use the overload Navigate(object,object) to pass data to the other view.

Call it like so

NavigationService n = NavigationService.GetNavigationService(this);
n.Navigate(new Uri("Test.xaml", UriKind.Relative), true);

And in your view you can extract the parameter that is passed by the Navigation.

void NavigationService_LoadCompleted(object sender, NavigationEventArgs e)
{
    bool test = (bool) e.ExtraData;
}

Upvotes: 0

Afshin
Afshin

Reputation: 1253

read this:

http://paulstovell.com/blog/wpf-navigation

Although it's not obvious, you can pass query string data to a page, and extract it from the path. For example, your hyperlink could pass a value in the URI:

<TextBlock>
    <Hyperlink NavigateUri="Page2.xaml?Message=Hello">Go to page 2</Hyperlink>
</TextBlock>

When the page is loaded, it can extract the parameters via NavigationService.CurrentSource, which returns a Uri object. It can then examine the Uri to pull apart the values. However, I strongly recommend against this approach except in the most dire of circumstances.

A much better approach involves using the overload for NavigationService.Navigate that takes an object for the parameter. You can initialize the object yourself, for example:

Customer selectedCustomer = (Customer)listBox.SelectedItem;
this.NavigationService.Navigate(new CustomerDetailsPage(selectedCustomer));

This assumes the page constructor receives a Customer object as a parameter. This allows you to pass much richer information between pages, and without having to parse strings.

Upvotes: 3

Related Questions