【问题标题】:Navigating from App.xaml.cs从 App.xaml.cs 导航
【发布时间】:2012-01-26 03:05:33
【问题描述】:

我想在我的应用程序的多个页面中添加一个应用程序栏。因此,我将应用程序栏定义为应用程序资源,以便它可以被多个页面使用。现在,这些按钮的事件处理程序位于App 类中,如http://msdn.microsoft.com/en-us/library/hh394043%28v=VS.92%29.aspx 所述。 但是,这些应用栏按钮基本上是重要页面的快捷方式。因此,单击一个按钮只会将您带到相应的页面。但是,由于我在App.xaml.cs 中定义了事件处理程序,它不允许我导航。我明白这其中的原因。但是,我不知道如何解决这个问题。

NavigationService.Navigate(new Uri("/Counting.xaml", UriKind.RelativeOrAbsolute));

说“非静态字段、方法或属性 System.Windows.Navigation.NavigationService.Navigate(System.Uri) 需要对象引用”

【问题讨论】:

    标签: c# windows-phone-7


    【解决方案1】:

    如果您可以访问框架,它会起作用吗?

    (Application.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri("/Counting.xaml", UriKind.RelativeOrAbsolute));
    

    编辑: 每个应用程序只有一个Frame。正是这个框架暴露了NavigationService。因此,NavigationService 始终可以通过框架访问,因为在任何 Windows Phone 应用程序中始终存在它的实例。由于您通常不会实例化一个新的NavigationService,因此很容易认为它是一个静态方法。但是,它实际上是一个非静态类,会在您的应用程序运行时自动实例化。在这种情况下,您所做的只是获取附加到始终存在的 Frame 的全局实例,并使用它在页面之间导航。这意味着您的类不必实例化或显式继承 NavigationService。

    【讨论】:

    • 非常感谢。有效。你能解释一下吗?
    • 不客气。我已经编辑了我的帖子 - 希望它能解释它为什么有效。
    【解决方案2】:

    从 App.xaml.cs(使用应用栏)导航到其他页面的另一种方法是使用 rootFrame var(在最后一行):

    private Frame rootFrame = null;
    protected override async void OnLaunched(LaunchActivatedEventArgs args)
    {
        ...
        SettingsPane.GetForCurrentView().CommandsRequested += App_CommandRequested;
    }
    
    private void App_CommandRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
    {
    SettingsCommand cmdSnir = new SettingsCommand("cmd_snir", "Snir's Page", 
                  new Windows.UI.Popups.UICommandInvokedHandler(onSettingsCommand_Clicked));
    args.Request.ApplicationCommands.Add(cmdSnir);
    }
    
    void onSettingsCommand_Clicked(Windows.UI.Popups.IUICommand command)
    {
    if (command.Id.ToString() == "cmd_snir")
          rootFrame.Navigate(typeof(MainPage)); //, UriKind.RelativeOrAbsolute);
    
    }
    

    【讨论】:

      【解决方案3】:

      我发现这种方法更好。 RootFrame 对象已经在 App.xaml.cs 文件中,您只需调用它即可。将它放在 UI 线程调度程序中也更安全。

       Deployment.Current.Dispatcher.BeginInvoke(() =>
                      {
                          // change UI here
                          RootFrame.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多