wpfnavigationquery-stringnavigateuri

Passing parameters to a WPF Page via its Uri


In the context of a navigation-style WPF application (NavigationWindow, not XBAP):

Is it possible for a Hyperlink's NavigateUri to contain extra parameters, like path data or a querystring? E.g., is there some way I could set my NavigateUri to /Product.xaml/123 or /Product.xaml?id=123, and have my Product.xaml page be able to see that it was called with a parameter of 123?


Solution

  • You can do this. See http://www.paulstovell.com/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.