开发者

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

This question already has answers here: How to pass values (parameters) between XAML pages? (2 answers) Closed 9 years ago.

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


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);
}


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.


I recommend looking at Caliburn.Micro!

http://caliburnmicro.codeplex.com

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜