问题
Passing value to another xaml page can be done easily with
NavigationService.Navigate(new Uri("/SecondPage.xaml?msg=" + textBox1.Text, UriKind.Relative));
But that is only for string values. I would like to pass an object to the xaml page. How do I do that?
Found a similar question on SO and WP7 forum. The solution is to use a global variable (not the nicest solution).
WP7: Pass parameter to new page?
http://social.msdn.microsoft.com/Forums/en-US/windowsphone7series/thread/81ca8713-809a-4505-8422-000a42c30da8
回答1:
Have a look at the default code created when you start a new DataBound Project. It shows a way of passing a reference to a selected object to a details page.
回答2:
Using OnNavigatedFrom method
OnNavigateFrom is called when we call the NavigationService.Navigate method. It has a NavigationEventArgs object as a parameter that returns the destination page with its Content property with which we can access a property of the destination page "DestinationPage.xaml.cs"
First, in the destination page "DestinationPage.xaml.cs", declare a property "SomeProperty":
public ComplexObject SomeProperty { get; set; }
Now, in "MainPage.xaml.cs", override the OnNavigatedFrom method:
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
// NavigationEventArgs returns destination page "DestinationPage"
DestinationPage dPage = e.Content as DestinationPage;
if (dPage != null)
{
// Change property of destination page
dPage.SomeProperty = new ComplexObject();
}
}
Now, get the SomeProperty value in "DestinationPage.xaml.cs":
private void DestinationPage_Loaded(object sender, RoutedEventArgs e)
{
// This will display a the Name of you object (assuming it has a Name property)
MessageBox.Show(this.SomeProperty.Name);
}
回答3:
I recommend looking at Caliburn.Micro!
http://caliburnmicro.codeplex.com
来源:https://stackoverflow.com/questions/4302212/how-to-pass-an-object-from-a-xaml-page-to-another