Mayson
Mayson

Reputation: 95

How to pass parameters between pages

I'm developing a UWP application that has two pages, I want the best practice to pass parameters between pages. I also want to pass information continuously and repeatedly

What is the best method for the following scenario?

For example, change user controls in the pages. We have two pages,each open and remain at the middle of the screen and a button on each page, which changes the background color of the other page when we click on it.

Thank you for your help,

Upvotes: 2

Views: 832

Answers (1)

Martin Zikmund
Martin Zikmund

Reputation: 39082

You can provide the navigation parameter as the as the second argument of the Frame.Navigate method:

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

And then get the parameter in the second page's OnNavigatedTo override:

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

The answers suggested as duplicates don't mention an important fact - the parameter can be only a basic type to enable navigation state serialization. As the documentation says:

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.

Even if you don't need to support suspension and frame state serialization, it is a good idea to stick with simple parameters and possibly store the date elsewhere. Again from documentation:

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.

If I need to pass a complex object, I usually tend to use JSON serialization to turn it into a string and then deserialize in the target page. For that you could use the awesome Json.NET library.

Upvotes: 1

Related Questions