Passing parameters between XAML pages is a fundamental aspect of effective application design. Whether you're navigating through pages in a Windows Phone, Silverlight, WPF, or Windows 8 application, understanding the appropriate methods for passing data will enhance your application's functionality and user experience.
For simple data transfer, the query string can be employed. Data passed through this method must be converted to strings and URL-encoded.
Navigating Page:
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; }
NavigationEventArgs provides access to parameters passed through method calls during navigation.
Navigating Page:
page.NavigationService.Navigate(new Uri("/Views/Page.xaml?parameter=test", UriKind.Relative)); // and ... protected override void OnNavigatedFrom(NavigationEventArgs e) { Page destinationPage = e.Content as Page; if (destinationPage != null) { destinationPage.PublicProperty = "String or object.."; } }
Destination Page:
// Use the value of "PublicProperty"..
Manual navigation allows custom parameter passing through the constructor.
Navigating Page:
page.NavigationService.Navigate(new Page("passing a string to the constructor"));
Destination Page:
public Page(string value) { // Use the value in the constructor... }
The key distinction lies in the application life cycle. Manually created pages are retained in memory, while pages navigated via Uri are not.
Method 1 and 2 can be used to pass complex objects, or alternatively, custom properties can be added to the Application class or data can be stored in Application.Current.Properties.
The above is the detailed content of How to Efficiently Pass Values Between XAML Pages?. For more information, please follow other related articles on the PHP Chinese website!