How to pass an object from a xaml page to another? [duplicate]

邮差的信 提交于 2020-01-10 03:11:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!