通过其Uri将参数传递给WPF页面

Joe*_*ite 10 navigation wpf navigateuri query-string

在导航样式的WPF应用程序(NavigationWindow,而不是XBAP)的上下文中:

Hyperlink的NavigateUri是否可以包含额外的参数,例如路径数据或查询字符串?例如,有什么方法可以将我的NavigateUri设置为/Product.xaml/123/Product.xaml?id=123,并让我的Product.xaml页面能够看到它被调用参数123

Pau*_*ell 17

你可以这样做.见http://www.paulstovell.com/wpf-navigation:

虽然不是很明显,但您可以将查询字符串数据传递给页面,并从路径中提取它.例如,您的超链接可以传递URI中的值:

<TextBlock>
    <Hyperlink NavigateUri="Page2.xaml?Message=Hello">Go to page 2</Hyperlink>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

加载页面时,它可以通过提取参数 NavigationService.CurrentSource,返回一个Uri对象.然后它可以检查Uri以拉开值.但是,除了在最严峻的情况下,我强烈建议不要采用这种方法.

一种更好的方法是使用NavigationService.Navigate的重载来获取参数的对象.您可以自己初始化对象,例如:

Customer selectedCustomer = (Customer)listBox.SelectedItem;
this.NavigationService.Navigate(new CustomerDetailsPage(selectedCustomer));
Run Code Online (Sandbox Code Playgroud)

这假设页面构造函数接收Customer对象作为参数.这允许您在页面之间传递更丰富的信息,而无需解析字符串.