C# 使用导航时,是否在Silverlight中将另一页的值传递给MainPage.xaml?

C# 使用导航时,是否在Silverlight中将另一页的值传递给MainPage.xaml?,c#,silverlight,xaml,navigation,C#,Silverlight,Xaml,Navigation,我在Silverlight中有一个页面,它是从MainPage.xaml导航的,名为OpenPage.xaml,然后我想将一个值传递回MainPage.xaml-此OpenPage.xaml使用以下方法调用: NavigationService.Navigate(new Uri("/OpenPage.xaml", UriKind.Relative)); 从主页-这不是主页的子项,因为RootVisual被替换-我可以称之为: NavigationService.Navigate(new Uri

我在Silverlight中有一个页面,它是从MainPage.xaml导航的,名为OpenPage.xaml,然后我想将一个值传递回MainPage.xaml-此OpenPage.xaml使用以下方法调用:

NavigationService.Navigate(new Uri("/OpenPage.xaml", UriKind.Relative));
从主页-这不是主页的子项,因为RootVisual被替换-我可以称之为:

NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
要返回到MainPage-但是我需要将值从OpenPage.xaml传递到MainPage.xaml-如何访问MainPage实例-我有一个名为Document的属性,但是当我这样做时:

        MainPage m = (MainPage)Application.Current.RootVisual;
        m.Document = "Hello World";
或者这个:

((MainPage)root).Document = "Hello World";
我得到一个无效的强制转换异常,因为我认为它正在尝试将OpenPage.xaml强制转换为MainPage.xaml-如何获取导航到页面,我想从OpenPage.xaml设置MainPage.xaml上的属性。

我还想将值从MainPage.xaml传递到另一个页面SavePage.xaml-但这有相同的问题-如何解决此问题?

使用查询字符串值:-

NavigationService.Navigate(new Uri("/MainPage.xaml?value=Hello%20World", UriKind.Relative);
MainPage
然后可以使用以下方法获取此值:-

string value =  this.NavigationContext.QueryString["value"];
编辑

响应注释,重新传递其他类型

一旦具备了上述功能,就可以使用其他服务模式传递其他类型的服务。例如,考虑一个实现:-< /P>的消息服务。
interface IMessageService
{
    Guid Store(object value)
    object Retrieve(Guid key)
}
然后,您将实现此接口并将实现公开为singleton,例如:-

public class MessageService : IMessageService
{
    public static IMessageService Default { // singleton stuff here }
}
您的OpenPage调用
MessageService.Default.Store
,并将结果Guid放入查询字符串中


然后,主页测试是否存在此类查询字符串值,如果存在,则使用其值调用
MessageService.Default.Retrieve
,从而从服务中删除该项。

这是一个有趣的解决方案-与ASP.NET QueryString类似,对于我当前的示例来说,这可能很好,但是,是否可以使用对象进行此操作,因为这对于页面之间更复杂的数据交互可能很有用。目前,我需要它作为独立存储的文件名,但我需要它用于以后的其他用途。谢谢。作为一个补充,在哪里以及如何最好地读取已传入的QueryString值。@RoguePlanetoid:我认为我已经显示的内容如何,在哪里?可能在OnNavigatedTo override中是最好的。谢谢-阅读第一种方法很好-但是第二种方法对于更复杂的示例也非常有用-这实际上是我正在编写的教程-完成后将发布链接。再次感谢!这个解决方案并不真正合适,因为您一直在向导航堆栈中添加内容,并且从不从中弹出值。
Partial Public Class MainPage
    Inherits UserControl

    Public Sub New()

        InitializeComponent()

        ContentFrame.Source = New Uri("/About", UriKind.Relative)

        ...............