Passing parameters to a WPF Page via its Uri

时光毁灭记忆、已成空白 提交于 2019-12-21 07:55:21

问题


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?


回答1:


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.




回答2:


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.




回答3:


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 collected because the whole instance will remain on Journal.



来源:https://stackoverflow.com/questions/1351546/passing-parameters-to-a-wpf-page-via-its-uri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!