从App.xaml.cs导航

时间:2011-12-22 13:20:58

标签: c# windows-phone-7

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

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

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

3 个答案:

答案 0 :(得分:24)

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

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

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

答案 1 :(得分:0)

从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);

}

答案 2 :(得分:0)

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

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