39

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

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

  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:通过将类型和参数作为对象传递来导航到页面
4

2 回答 2

88

传递参数的方法

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.

于 2012-09-16T06:17:03.700 回答
0

对于那些仍然有问题的人,因为他们没有 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 }
}
于 2022-01-11T23:56:58.473 回答