How to pass values ​​(parameters) between XAML pages?

Similar questions were asked before, but this question is trying to explore more possibilities and the ability to transfer complex objects.

The question is how to pass parameters, but it really needs to be divided into three parts.

  • When moving between pages in a XAML application, how do you pass parameters?
  • What is the difference between using URI navigation and manual navigation?
  • How to pass objects (not just strings) when using Uri navigation?

Uri navigation example

page.NavigationService.Navigate(new Uri("/Views/Page.xaml", UriKind.Relative)); 

Manual navigation example

 page.NavigationService.Navigate(new Page()); 

The answer to this question applies to WP7, Silverlight, WPF, and Windows 8.

Note. There is a difference between Silverlight and Windows8

  • Windows phone: pages switch to Uri and data passed as a query string or instance
  • Windows 8 : pages are moved by type passing, and parameters as objects
+35
c # windows-8 windows-phone wpf xaml
Sep 16 '12 at 6:17
source share
1 answer

Methods for passing parameters

1. Using the query string

You can pass parameters through the query string using this method, which means you need to convert your data into strings and encode their URLs. You should only use this to transmit simple data.

Page navigation:

 page.NavigationService.Navigate(new Uri("/Views/Page.xaml?parameter=test", UriKind.Relative)); 

Destination Page:

 string parameter = string.Empty; if (NavigationContext.QueryString.TryGetValue("parameter", out parameter)) { this.label.Text = parameter; } 

2. Using NavigationEventArgs

Page navigation:

 page.NavigationService.Navigate(new Uri("/Views/Page.xaml?parameter=test", UriKind.Relative)); // and .. protected override void OnNavigatedFrom(NavigationEventArgs e) { // NavigationEventArgs returns destination page Page destinationPage = e.Content as Page; if (destinationPage != null) { // Change property of destination page destinationPage.PublicProperty = "String or object.."; } } 

Destination Page:

 // Just use the value of "PublicProperty".. 

3. Using manual navigation

Page navigation:

 page.NavigationService.Navigate(new Page("passing a string to the constructor")); 

Destination Page:

 public Page(string value) { // Use the value in the constructor... } 

The difference between Uri and manual navigation

I think the main difference here is the application life cycle. Manually created pages are stored in memory for navigation purposes. Read more about it here .

Complex Object Transfer

You can use one or two methods to transfer complex objects (recommended). You can also add custom properties to the Application class or save data to Application.Current.Properties .

+79
Sep 16 '12 at 6:17
source share
— -



All Articles