如何将参数传递给另一个页面并在WPF中读取它?我在互联网上读到这可以使用URL完成,如下所示:
NavigationService n = NavigationService.GetNavigationService(this);
n.Navigate(new Uri("Test.xaml?param=true", UriKind.Relative));
但我无法读取Test.xaml
页面中的参数值。
我无法从页面实例化一个新实例并通过构造函数传递它,因为我在使用页面路径进行往返之前遇到了问题。
答案 0 :(得分:2)
请阅读:
http://paulstovell.com/blog/wpf-navigation
虽然不是很明显,但您可以将查询字符串数据传递给页面,并从路径中提取它。例如,您的超链接可以传递URI中的值:
<TextBlock>
<Hyperlink NavigateUri="Page2.xaml?Message=Hello">Go to page 2</Hyperlink>
</TextBlock>
加载页面时,它可以通过NavigationService.CurrentSource提取参数,后者返回一个Uri对象。然后它可以检查Uri以拉开值。但是,除了在最严峻的情况下,我强烈建议不要使用这种方法。
更好的方法是使用带有参数对象的NavigationService.Navigate的重载。您可以自己初始化对象,例如:
Customer selectedCustomer = (Customer)listBox.SelectedItem;
this.NavigationService.Navigate(new CustomerDetailsPage(selectedCustomer));
这假定页面构造函数接收Customer对象作为参数。这允许您在页面之间传递更丰富的信息,而无需解析字符串。
答案 1 :(得分:1)
您可以使用重载Navigate(object,object)将数据传递到另一个视图。
这样称呼
NavigationService n = NavigationService.GetNavigationService(this);
n.Navigate(new Uri("Test.xaml", UriKind.Relative), true);
在您的视图中,您可以提取导航传递的参数。
void NavigationService_LoadCompleted(object sender, NavigationEventArgs e)
{
bool test = (bool) e.ExtraData;
}