Today’s post will be a small tip about how we can pass multiple parameters when navigating to another page in a Windows Store app.
Frame.Navigate() method, which is used for navigating to another page, allows us to send a parameter to the new page like this:
string parameter = "The information that you wish to send to the next page."; Frame.Navigate(typeof(AnotherPage), parameter);
Then we get the parameter in OnNavigatedTo() function of AnotherPage, like this:
protected override void OnNavigatedTo(NavigationEventArgs e) { string passedParameter = e.Parameter.ToString(); }
So basically we can send any object we want this way. But what if we want to send more than one parameter (which is quite common)? We can not just do it like this:
string parameter = "The information that you wish to send to the next page."; int parameter2 = 5; Frame.Navigate(typeof(AnotherPage), argument, argument2);
In this case, we can use application level global variables (but that isn’t good practice, really), or we can use the following way of navigation instead of Frame.Navigate():
string parameter = "The information that you wish to send to the next page."; int parameter2 = 5; Window.Current.Content = new AnotherPage(parameter, parameter2);
public AnotherPage(string firstArgument, int secondArgument) { this.InitializeComponent(); }
If we use Window.Current.Content to change the page, we forgo the navigation support, and if you have more than a few pages in our app, going back and forth becomes very impractical and ineffective since you have to do everything manually.
Therefore, we can create a custom class called AnotherPagePayload instead, set our parameters in it, and send that object:
public class AnotherPagePayload { public string parameter1 { get; set; } public int parameter2 { get; set; } }
AnotherPagePayload payload = new AnotherPagePayload(); payload.parameter1 = "Information you want to send to the next page."; payload.parameter2 = 5; Frame.Navigate(typeof(AnotherPage), payload);
And then retrieve it like this, in AnotherPage:
protected override void OnNavigatedTo(NavigationEventArgs e) { AnotherPagePayload passedParameter = e.Parameter as AnotherPagePayload; string parameter1 = passedParameter.parameter1; int parameter2 = passedParameter.parameter2; }
That’s it. It’s a small detail, but if you don’t know how to do it when you start developing your app, correcting it later takes some time.
Thank you for reading.
What is diference of mode pass data? Whats is the best?