c# - 如何在页面之间传递参数

标签 c# xaml uwp

我正在开发一个有两个页面的 UWP 应用程序,我希望最佳做法是在页面之间传递参数。 我也想不断重复传递信息

以下场景的最佳方法是什么?

例如,更改页面中的用户控件。 我们有两个页面,每个页面都打开并保持在屏幕中间,每个页面上都有一个按钮,当我们点击它时,它会改变另一个页面的背景颜色。

谢谢你的帮助,

最佳答案

您可以提供导航参数作为 Frame.Navigate 方法的第二个参数:

Frame.Navigate(typeof(SecondPage),"something");

然后在第二页的OnNavigatedTo override中获取参数:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    var data = (string)e.Parameter; //"something"
    ...
}

作为重复建议的答案没有提到一个重要的事实 - 参数只能是启用导航状态序列化的基本类型。正如文档所说:

To enable frame state serialization using GetNavigationState, you must use only basic types for the navigation parameter, such as string, char, numeric, and GUID types. Otherwise GetNavigationState will throw an exception when the app suspends. The parameter can have other types if you do not use GetNavigationState.

即使您不需要支持暂停和帧状态序列化,坚持使用简单参数并可能将日期存储在其他地方也是一个好主意。再次来自文档:

The parameter value can have a complex type if you do not use GetNavigationState. However, you should still use only basic types in order to avoid excess memory usage caused by the frame’s navigation stack holding a reference to the parameter. A preferred approach is to not pass the actual object, but instead pass an identifier that you can use to look up the object in the target landing page. For example, instead of passing a Customer object, pass a reference to the CustomerID, then look up the Customer after the navigation is complete.

如果我需要传递一个复杂的对象,我通常倾向于使用JSON序列化将它变成一个string,然后在目标页面反序列化。为此,您可以使用很棒的 Json.NET library .

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

相关文章:

c# - UWP/C# : ObservableCollection sort in-place (w/o scrolling)

c# - 如何从以指定访问模式运行的 UWP 应用程序关闭 Windows 平板电脑?

c# - 如何捕捉扩展器标题点击事件

c# - Windows 服务无法获得正确的系统文化

c# - GZipStream.Write 方法

wpf - 设计时错误(未找到可附加属性 x)

wpf - 打印 WPF DataGrid 内容

wpf - DevExpress WPF GridControl : How to set a default sort in XAML

c# - 有没有办法以管理员权限运行 UWP 应用程序?

c# - SqlException (0x80131904) 连接到 mdf 数据库