Reputation: 17263
Similar questions have been asked before but this question strives to explore more options and the ability to pass complex objects.
The question is how to pass parameters but it really needs to be broken up into three parts..
Example of Uri navigation
page.NavigationService.Navigate(new Uri("/Views/Page.xaml", UriKind.Relative));
Example of manual navigation
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
Upvotes: 40
Views: 80178
Reputation: 77
For those still having issues because they don't an onNavigatedTo function to override and use a frame to navigate, this is what I used.
In the page you are navigating from: lets say this page is called "StartPoint.xaml"
NameOfFrame.Navigate(new System.Uri("Destination.xaml", UriKind.RelativeOrAbsolute), ValueToBePassed);
string code = "hello world";
)On the Destination.xaml page : Create the page load event.
Destinations.xaml > load
private string x;
private void Page_Loaded(object sender, RoutedEventArgs e)
{
x = StartPoint.ValueToBePassed;
//Call functions or do other stuff while im here
//e.g. if (x != "") { please work you damn code }
// else { go to sleep and forget about the worries }
}
Upvotes: 1
Reputation: 17263
1. Using the query string
You can pass parameters through the query string, using this method means have to convert your data to strings and url encode them. You should only use this to pass simple data.
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;
}
2. Using NavigationEventArgs
Navigating page:
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
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...
}
I think the main difference here is the application life cycle. Pages created manually are kept in memory for navigation reasons. Read more about it here.
You can use method one or two to pass complex objects (recommended). You can also add custom properties to the Application
class or store data in Application.Current.Properties
.
Upvotes: 90