从App.xaml.cs导航

我想在我的应用程序的多个页面中添加一个应用程序栏。 因此,我将应用程序栏定义为应用程序资源,以便多个页面可以使用它。 现在,这些按钮的事件处理程序位于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)”需要对象引用“

如果您可以访问框架,它是否有效?

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

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

另一种从App.xaml.cs导航到其他页面的方法(使用app栏)使用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); } 

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

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