如何将参数传递给另一个 WPF 页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19088180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass a parameter to another WPF page
提问by Homam
How to pass a parameter to another page and read it in WPF? I read on the internet that this could be done using the URL as the following:
如何将参数传递给另一个页面并在 WPF 中读取它?我在互联网上读到这可以使用 URL 来完成,如下所示:
NavigationService n = NavigationService.GetNavigationService(this);
n.Navigate(new Uri("Test.xaml?param=true", UriKind.Relative));
But I'm not able to read the parameter value in the Test.xamlpage.
但是我无法读取Test.xaml页面中的参数值。
I cannot instantiate a new instance from the page and pass it by the constructor because I had a problem before the round-trip was to navigate using the page path.
我无法从页面实例化新实例并通过构造函数传递它,因为在往返使用页面路径导航之前我遇到了问题。
回答by Afshin
read this:
读这个:
http://paulstovell.com/blog/wpf-navigation
http://paulstovell.com/blog/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:
虽然不明显,但您可以将查询字符串数据传递给页面,并从路径中提取它。例如,您的超链接可以在 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.
当页面加载时,它可以通过 NavigationService.CurrentSource 提取参数,它返回一个 Uri 对象。然后它可以检查 Uri 以分离这些值。但是,我强烈建议不要使用这种方法,除非在最可怕的情况下。
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:
一个更好的方法是使用 NavigationService.Navigate 的重载,该重载接受一个对象作为参数。您可以自己初始化对象,例如:
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.
这假设页面构造函数接收一个 Customer 对象作为参数。这允许您在页面之间传递更丰富的信息,而无需解析字符串。
回答by Jehof
You can use the overload Navigate(object,object)to pass data to the other view.
您可以使用重载Navigate(object,object)将数据传递到另一个视图。
Call it like so
像这样称呼
NavigationService n = NavigationService.GetNavigationService(this);
n.Navigate(new Uri("Test.xaml", UriKind.Relative), true);
And in your view you can extract the parameter that is passed by the Navigation.
在您的视图中,您可以提取导航传递的参数。
void NavigationService_LoadCompleted(object sender, NavigationEventArgs e)
{
bool test = (bool) e.ExtraData;
}

