如何将对象从xaml页面传递到另一个页面?

时间:2010-11-29 09:06:01

标签: xaml windows-phone-7

使用

可以轻松地将值传递到另一个xaml页面

NavigationService.Navigate(new Uri("/SecondPage.xaml?msg=" + textBox1.Text, UriKind.Relative));

但这仅适用于字符串值。我想将一个对象传递给xaml页面。我该怎么做?

在SO和WP7论坛上发现了类似的问题。解决方案是使用全局变量(不是最好的解决方案)。

WP7: Pass parameter to new page?

http://social.msdn.microsoft.com/Forums/en-US/windowsphone7series/thread/81ca8713-809a-4505-8422-000a42c30da8

3 个答案:

答案 0 :(得分:5)

使用OnNavigatedFrom方法

在调用NavigationService.Navigate方法时调用OnNavigateFrom。它有一个NavigationEventArgs对象作为参数返回目标页面及其Content属性,我们可以使用它来访问目标页面“DestinationPage.xaml.cs”的属性

首先,在目标页面“DestinationPage.xaml.cs”中,声明属性“SomeProperty”:

public ComplexObject SomeProperty { get; set; }

现在,在“MainPage.xaml.cs”中,重写OnNavigatedFrom方法:

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

现在,在“DestinationPage.xaml.cs”中获取SomeProperty值:

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

答案 1 :(得分:3)

查看启动新DataBound项目时创建的默认代码。它显示了一种将对所选对象的引用传递给详细信息页面的方法。

答案 2 :(得分:1)

我建议看看Caliburn.Micro!

http://caliburnmicro.codeplex.com

相关问题