Rog*_*oid 5 c# navigation silverlight xaml
我在Silverlight的一个网页,其中从MainPage.xaml中航海下,所谓的OpenPage.xaml,那么我想传递一个值回到MainPage.xaml中 - 这OpenPage.xaml被称为使用这样的:
NavigationService.Navigate(new Uri("/OpenPage.xaml", UriKind.Relative));
Run Code Online (Sandbox Code Playgroud)
从主页 - 这不是MainPage的子节点,因为RootVisual被替换 - 我可以这样称呼:
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
Run Code Online (Sandbox Code Playgroud)
要返回MainPage - 但是我需要将一个值从OpenPage.xaml传递给MainPage.xaml - 如何访问MainPage实例 - 我有一个名为Document的属性但是当我这样做时:
MainPage m = (MainPage)Application.Current.RootVisual;
m.Document = "Hello World";
Run Code Online (Sandbox Code Playgroud)
或这个:
((MainPage)root).Document = "Hello World";
Run Code Online (Sandbox Code Playgroud)
我得到一个无效转换异常,因为我认为这是试图将OpenPage.xaml转换为MainPage.xaml中-如何我得到的NavigatedTo页,我想设置从OpenPage.xaml上MainPage.xaml中的财产.
我还想将值从MainPage.xaml传递到另一个页面SavePage.xaml - 但这有同样的问题 - 我该如何解决这个问题?
使用查询字符串值: -
NavigationService.Navigate(new Uri("/MainPage.xaml?value=Hello%20World", UriKind.Relative);
Run Code Online (Sandbox Code Playgroud)
MainPage 然后可以使用以下方法获取此值: -
string value = this.NavigationContext.QueryString["value"];
Run Code Online (Sandbox Code Playgroud)
编辑:
回应评论重新传递其他类型.
完成上述操作后,您可以使用其他服务模式传递其他类型.例如,考虑一个实现的MessageService: -
interface IMessageService
{
Guid Store(object value)
object Retrieve(Guid key)
}
Run Code Online (Sandbox Code Playgroud)
然后,您将实现此接口并将实现公开为单例说: -
public class MessageService : IMessageService
{
public static IMessageService Default { // singleton stuff here }
}
Run Code Online (Sandbox Code Playgroud)
您的OpenPage调用MessageService.Default.Store并将生成的Guid放在查询字符串中.
然后MainPage测试是否存在这样的查询字符串值(如果存在)使用其值来调用MessageService.Default.Retrieve,从服务中删除该项.