【问题标题】:Pass value from another page to MainPage.xaml in Silverlight when using Navigation?使用导航时将值从另一个页面传递到 Silverlight 中的 MainPage.xaml?
【发布时间】:2010-03-23 13:39:20
【问题描述】:

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

NavigationService.Navigate(new Uri("/OpenPage.xaml", UriKind.Relative));

从主页 - 这不是 MainPage 的子页面,因为 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 - 如何获取 NavigatedTo 页面,我想从 OpenPage.xaml 设置 MainPage.xaml 上的属性。 我还想将 MainPage.xaml 中的值传递到另一个页面 SavePage.xaml - 但这有同样的问题 - 我该如何解决这个问题?

【问题讨论】:

    标签: c# silverlight xaml navigation


    【解决方案1】:

    使用查询字符串值:-

    NavigationService.Navigate(new Uri("/MainPage.xaml?value=Hello%20World", UriKind.Relative);
    

    MainPage 然后可以使用以下方法获取此值:-

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

    编辑

    响应重新传递其他类型的评论。

    一旦您具备上述条件,您就可以使用其他服务模式来传递其他类型。例如考虑一个 MessageService 实现:-

    interface IMessageService
    {
        Guid Store(object value)
        object Retrieve(Guid key)
    }
    

    然后,您将实现此接口并将实现公开为单例:-

    public class MessageService : IMessageService
    {
        public static IMessageService Default { // singleton stuff here }
    }
    

    您的 OpenPage 调用 MessageService.Default.Store 并将生成的 Guid 放入查询字符串中。

    MainPage 然后测试是否存在这样的查询字符串值,如果存在,则使用它的值调用MessageService.Default.Retrieve,这会从服务中删除该项目。

    【讨论】:

    • 这是一个有趣的解决方案 - 就像 ASP.NET QueryStrings,这对于我当前的示例可能很好,但是是否可以使用对象来执行此操作,因为这对于页面之间更复杂的数据交互可能很有用.目前我需要它作为隔离存储的文件名,但我以后需要它用于其他用途。谢谢。
    • 作为附加的在何处以及如何最好地读取已传入的 QueryString 值。
    • @RoguePlanetoid:我认为我已经展示的内容怎么样,在哪里?可能在 OnNavigatedTo 覆盖中是最好的。
    • 谢谢 - 第一种方式阅读效果很好 - 但第二种方式对于更复杂的示例也非常有用 - 这实际上是针对我正在编写的教程 - 完成后将发布链接。再次感谢!
    • 这个解决方案并不合适,因为您一直在向导航堆栈添加内容并且从不从中弹出值。
    【解决方案2】:
    Partial Public Class MainPage
        Inherits UserControl
    
        Public Sub New()
    
            InitializeComponent()
    
            ContentFrame.Source = New Uri("/About", UriKind.Relative)
    
            ...............
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      相关资源
      最近更新 更多