gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:00:51 26 4
gpt4 key购买 nike

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

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

  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和Windows8是有区别的

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

最佳答案

传递参数的方法

<强>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与手动导航的区别

我认为这里的主要区别是应用程序生命周期。出于导航原因,手动创建的页面保存在内存中。了解更多信息 here .

传递复杂对象

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

关于c# - 如何在 XAML 页面之间传递值(参数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12444816/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com