将对象传递到下一页

Passing an object to next Page

我有一个 List<accounts> accountslist 想要传递到框架中的另一个页面,但是当我导航到下一个页面时我的应用程序崩溃了。

C#:在 First 页面上,

//above this, there are codes that deserialize the List data from
//phone's storage
List<accounts> accountslist;

Frame.Navigate(typeof(Second), accountslist); 
//Second is the second page that I want the accountlist to go to.. 

这是在 Second 页面上:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    List<accounts> accountslist = e.Parameter as List<accounts>;
    //when Second frame is about to be displayed,
    //the app crashed, :(
}

我已经在 Second 页面上尝试 this.Loaded 从 phone 的存储中反序列化 accountslist,但结果仍然相同(应用First 页面 loaded/navigated 时崩溃。)

我很确定我明白你的意思。您有一个包含多个页面的框架。而且,您在第一页中有数据要通过 Navigate() 方法发送到第二页,对吗?

Frame 的 Navigate() 方法包括一个显示在接收页面的 OnNavigatedTo() 覆盖方法中的参数参数。这是将参数从一个页面发送到另一个页面的最快和最简单的方法。

话虽这么说,但我不是这样做的。我不这样做的原因是因为 MSDN 建议您只传递一个字符串。为什么?因为(这听起来有点高级)当您处理应用程序的暂停时,该操作的一部分是序列化导航堆栈。

When I need to pass information from one Page to another the important thing I need to remember is that whatever I am passing needs to be recreate-able should the app be resumed after termination. So if I had a class I needed to pass from Page one to Page two, I would first ensure the data is serialized somewhere else (in a remote database, in a local database, or in the local file system) and then pass to Page 2 only the string necessary for it to locate and deserialize the data. This sounds like a seriously complex extra step but it does mean the user's experience across state transition is smooth and painless. It is more work for the developer but a better experience for the user.

更多信息:http://blogs.msdn.com/b/mspfe/archive/2013/06/17/suspend-and-resume-in-winrt.aspx

与此同时,在 Frame.Navigate() 中传递参数然后在 Page.OnNavigatedTo() 中接收它是一个很好的起点,直到您开始为您的应用添加更多复杂性。

祝你好运!