Passing parameters to a WPF Page via its Uri Passing parameters to a WPF Page via its Uri wpf wpf

Passing parameters to a WPF Page via its Uri


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.


Another way is to create a public variable on the destiny page and use a get/set property to assign a value to it.

On Page:

private Int32 pMyVar;public Int32 MyVar{   get { return this.pMyVar; }   set { this.pMyVar = value; }}

When navigating to it:

MyPagePath.PageName NewPage = new MyPagePath.PageName();NewPage.MyVar = 10;this.MainFrameName.NavigationService.Navigate(NewPage);

When NewPage is loaded, the integer MyVar will be equal to 10.MainFrameName is the frame you are using in case you are working with frame, but if not, the navigate command remains the same regardless.Its my opinion, but it seems easier to track it that way, and more user friendly to those who came from C# before WPF.


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

Paul Stovell I think that using your suggestion will make your pages not garbage collectedbecause the whole instance will remain on Journal.