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

Dan*_*tle 37 c# wpf xaml windows-phone windows-8

之前已经提出了类似的问题,但这个问题努力探索更多选项和传递复杂对象的能力.

问题是如何传递参数,但它确实需要分解为三个部分.

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

Uri导航示例

page.NavigationService.Navigate(new Uri("/Views/Page.xaml", UriKind.Relative));
Run Code Online (Sandbox Code Playgroud)

手动导航示例

page.NavigationService.Navigate(new Page());
Run Code Online (Sandbox Code Playgroud)

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

注意:Silverlight和Windows8之间存在差异

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

Dan*_*tle 86

传递参数的方法

1.使用查询字符串

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

浏览页面:

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

目的地页面:

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

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..";
    }
}
Run Code Online (Sandbox Code Playgroud)

目的地页面:

// Just use the value of "PublicProperty"..
Run Code Online (Sandbox Code Playgroud)

3.使用手动导航

浏览页面:

page.NavigationService.Navigate(new Page("passing a string to the constructor"));
Run Code Online (Sandbox Code Playgroud)

目的地页面:

public Page(string value) {
    // Use the value in the constructor...
}
Run Code Online (Sandbox Code Playgroud)

Uri和手动导航之间的区别

我认为这里的主要区别是应用程序生命周期.由于导航原因,手动创建的页面会保留在内存中.在这里阅读更多相关信息.

传递复杂的物体

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

  • 还可以注意到`NavigationContext.QueryString.TryGetValue("parameter",out参数)`需要从以下方法中调用:`protected override void OnNavigatedTo(NavigationEventArgs e)` (5认同)