如何在 XAML 页面之间传递值(参数)? [英] How to pass values (parameters) between XAML pages?

查看:37
本文介绍了如何在 XAML 页面之间传递值(参数)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前有人问过类似的问题,但这个问题力求探索更多选项和传递复杂对象的能力.

问题是如何传递参数,但确实需要分成三部分..

The question is how to pass parameters but it really needs to be broken up into three parts..

  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.

The answer to this question applies to WP7, silverlight, WPF and Windows 8.

注意:Silverlight 和 Windows8 有区别

Note: There is a difference between Silverlight and Windows8

  • Windows Phone:使用 Uri 和作为查询字符串或实例传递的数据导航到页面
  • Windows 8:通过传递类型和参数作为对象来导航到页面
  • Windows Phone: pages are navigated to using a Uri and data passed as a query string or an instance
  • Windows 8: pages are navigated to by passing the type, and parameters as objects

推荐答案

传递参数的方法

1.使用查询字符串

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

You can pass parameters through the query string, using this method means have to convert your data to strings and url encode them. You should only use this to pass simple data.

导航页面:

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 中.

You can use method one or two to pass complex objects (recommended). You can also add custom properties to the Application class or store data in Application.Current.Properties.

这篇关于如何在 XAML 页面之间传递值(参数)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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