如何在XAML页面之间传递数值(参数)?

40

之前曾有类似的问题,但这个问题力图探索更多选项和传递复杂对象的能力。

该问题是如何传递参数,但实际上它需要分成三个部分:

  1. 在XAML应用程序中导航页面时,如何传递参数?
  2. 使用Uri导航和手动导航有什么区别?
  3. 在使用Uri导航时如何传递对象(而不仅仅是字符串)?

Uri导航示例

page.NavigationService.Navigate(new Uri("/Views/Page.xaml", UriKind.Relative));

手动导航示例

page.NavigationService.Navigate(new Page());

这个问题的答案适用于WP7、Silverlight、WPF和Windows 8。

注意:Silverlight和Windows 8之间存在差异

  • Windows Phone: 使用Uri导航到页面,并将数据作为查询字符串或实例传递。
  • Windows 8:通过传递类型和对象参数来导航到页面。
2个回答

90

传递参数的方法

1. 使用查询字符串

您可以通过查询字符串传递参数,使用此方法意味着必须将数据转换为字符串并对其进行URL编码。您应该仅在传递简单数据时使用此方法。

导航页面:

page.NavigationService.Navigate(new Uri("/Views/Page.xaml?parameter=test", UriKind.Relative));

目标页面:

string parameter = string.Empty;
if (NavigationContext.QueryString.TryGetValue("parameter", out parameter)) {
    this.label.Text = parameter;
}

2. 使用 NavigationEventArgs

导航到页面:

page.NavigationService.Navigate(new Uri("/Views/Page.xaml?parameter=test", UriKind.Relative));

// and ..

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    // NavigationEventArgs returns destination page
    Page destinationPage = e.Content as Page;
    if (destinationPage != null) {

        // Change property of destination page
        destinationPage.PublicProperty = "String or object..";
    }
}

目标页面:

// Just use the value of "PublicProperty"..

3. 使用手动导航

页面导航:

page.NavigationService.Navigate(new Page("passing a string to the constructor"));

目标页面:

public Page(string value) {
    // Use the value in the constructor...
}

Uri和手动导航之间的区别

我认为这里的主要区别在于应用程序的生命周期。手动创建的页面将因导航原因而保留在内存中。了解更多信息,请阅读此处

传递复杂对象

您可以使用方法一或方法二来传递复杂对象(建议使用)。您还可以向Application类添加自定义属性或将数据存储在Application.Current.Properties中。


7
需要注意的是,NavigationContext.QueryString.TryGetValue("parameter", out parameter)需要在以下方法内被调用:protected override void OnNavigatedTo(NavigationEventArgs e) - Vishal
typeof运算符的导航怎么样?你没有写任何关于它的内容。 - fnc12

1

对于那些仍然遇到问题的人,因为他们没有onNavigatedTo函数来覆盖和使用框架进行导航,这是我使用的方法。

在你要导航的页面中: 假设这个页面叫做“StartPoint.xaml”

NameOfFrame.Navigate(new System.Uri("Destination.xaml", UriKind.RelativeOrAbsolute), ValueToBePassed);

  • 在我的情况下,ValueToBePassed是一个简单的字符串,我没有尝试过使用对象。(通过简单的字符串,我指的是string code = "hello world";

在Destination.xaml页面上:

  • 创建页面加载事件。
  • 这可以通过转到页面的属性窗口>事件>已加载>双击加载旁边的字段来完成,以自动生成函数并转到代码后台中的函数。

Destinations.xaml>加载

private string x;

private void Page_Loaded(object sender, RoutedEventArgs e)
{
   x = StartPoint.ValueToBePassed;
   //Call functions or do other stuff while im here
   //e.g. if (x != "") { please work you damn code }
   //     else { go to sleep and forget about the worries }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接