2011-12-22 21 views
9

我想將應用程序欄添加到我的應用程序的多個頁面。所以,我將應用程序欄定義爲應用程序資源,以便它可以被多個頁面使用。現在,這些按鈕的事件處理程序位於App類中,如此處所述http://msdn.microsoft.com/en-us/library/hh394043%28v=VS.92%29.aspx。 但是,這些應用欄按鈕基本上是重要頁面的快捷方式。所以,點擊一個按鈕就會把你帶到相應的頁面。但是,由於我在App.xaml.cs中定義事件處理程序,因此它不允許我導航。我明白這個的原因。但是,我不知道如何解決這個問題。從App.xaml.cs導航

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

說「的對象引用需要非靜態字段,方法或屬性System.Windows.Navigation.NavigationService.Navigate(的System.Uri)」

回答

24

請問如果你訪問它的工作到框架?

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

編輯: 每個應用程序只有一個Frame。這是暴露NavigationService的這個框架。因此,NavigationService始終可以通過框架訪問,因爲在任何Windows Phone應用程序中總會有一個實例。既然你通常沒有實例化一個新的NavigationService,很容易認爲它是一個靜態方法。但是,它實際上是一個非靜態的類,當您的應用運行時會自動實例化。在這種情況下,你所做的就是獲取全局實例,該實例連接到始終存在的幀,並使用它在頁面之間進行導航。這意味着您的類不必實例化或顯式繼承NavigationService。

+0

非常感謝。有效。你能解釋一下這個嗎? – Divya 2011-12-22 13:47:33

+2

不客氣。我編輯了我的文章 - 希望它解釋了爲什麼它的作品。 – keyboardP 2011-12-22 13:56:14

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

} 
0

一。 RootFrame對象已經在App.xaml.cs文件中,您只需要調用它。把這個放在UI線程調度器中也是比較安全的。

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

爲什麼更安全? – GBU 2016-01-05 14:10:26