通过其Uri将参数传递到WPF页面 [英] Passing parameters to a WPF Page via its Uri

查看:494
本文介绍了通过其Uri将参数传递到WPF页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

超链接的NavigateUri是否可能包含额外的参数,例如路径数据或查询字符串?例如,是否可以通过某种方式将NavigateUri设置为/Product.xaml/123/Product.xaml?id=123,并让我的Product.xaml页面能够看到它是用123参数调用的?

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?

推荐答案

您可以执行此操作.参见 http://www.paulstovell.com/wpf-navigation :

You can do this. See http://www.paulstovell.com/wpf-navigation:

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

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>

页面加载后,可以 通过提取参数 NavigationService.CurrentSource,其中 返回一个Uri对象.然后可以 检查Uri拆开 价值观.但是,我强烈建议 反对这种方法,除了 最可怕的情况.

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.

更好的方法涉及使用 的过载 NavigationService.Navigate需要 参数的对象.你可以 自己初始化对象,因为 例如:

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));

这假设页面构造函数 收到一个Customer对象作为 范围.这可以让您通过 页面之间的信息要丰富得多, 无需解析字符串.

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.

这篇关于通过其Uri将参数传递到WPF页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆