Passing an object to next Page

时间:2015-07-28 15:45:25

标签: c# xaml windows-runtime windows-phone-8.1 winrt-xaml

I have a List<accounts> accountslist that I want to pass to another Page in the Frame, but my app crashes when I navigate to the next Page.

C#: this is on the First Page,

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

this is on the Second Page:

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, :(
}

I have tried this.Loaded on the Second Page to deserialize the accountslist from the phone's storage, but the result is still the same (the app crashed when it is loaded/navigated from the First Page.)

1 个答案:

答案 0 :(得分:1)

I'm pretty sure I know what you mean. You have a single frame with multiple pages. And, you have data in the first page you want to send to the second page by way of the Navigate() method, right?

The Navigate() method of the Frame include a parameter argument that shows up in the receiving Page's OnNavigatedTo() override method. This is the fastest and easiest way to send parameters from one Page to another.

That being said, this is not how I do it. The reason I do not do it this way is because MSDN recommends you pass only a string. Why? Because (and this sounds a little advanced for where you are now) when you handle the suspension of your app, part of that operation is to serialize the navigation stack.

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.

More information: http://blogs.msdn.com/b/mspfe/archive/2013/06/17/suspend-and-resume-in-winrt.aspx

In the meantime, passing the parameter in Frame.Navigate() and then receiving it in Page.OnNavigatedTo() is a great place to start until you start to add more sophistication to your app.

Best of luck!