2011-11-22 73 views
1

正如您所看到的,我想導航到「ScoreInputDialog.xaml」頁面,用戶可以在其中鍵入一個名稱。在此之後,我試圖將名稱保存到列表中,但它總是空的,因爲最終導航到頁面「ScoreInputDialog.xaml」正在完成。在繼續執行其他代碼之前,如何導航到期望的頁面並獲取我的價值?爲什麼NavigationService.Navigate只在最後運行?

NavigationService.Navigate(new Uri("/ScoreInputDialog.xaml", UriKind.Relative)); // Sets tempPlayerName through a textbox. 
if (phoneAppService.State.ContainsKey("tmpPlayerName")) 
{ 
    object pName; 
    if (phoneAppService.State.TryGetValue("tmpPlayerName", out pName)) 
    { 
     tempPlayerName = (string)pName; 
    } 
} 
highScorePlayerList.Add(tempPlayerName); 

回答

2

您應該Navigate電話後直接做任何事。相反,覆蓋你是從,得到通知來的頁面OnNavigatedTo方法,當用戶回來

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) 

當用戶按下退出「ScoreInputDialog.xaml」,或許這個方法會被調用後退按鈕或因爲您致電NavigationService.GoBack()。這將退出「ScoreInputDialog.xaml」頁面並轉到上一頁,在那裏將調用OnNavigatedTo。這是檢查價值的時間。

插圖導航流量:

「OriginPage」 --- [Navigate] ---> 「ScoreInputDialog」 --- [GoBack()或後退按鈕] ---> 「OriginPage」(*)

(*)在那裏將調用OnNavigatedTo。實施看起來是這樣的:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) 
{ 
    if (phoneAppService.State.ContainsKey("tmpPlayerName")) 
    { 
     object pName; 
     if (phoneAppService.State.TryGetValue("tmpPlayerName", out pName)) 
     { 
      tempPlayerName = (string)pName; 
     } 
     highScorePlayerList.Add(tempPlayerName); 
    } 
} 

記住調用Navigate之前清除臨時球員的名字:

phoneAppService.State.Remove("tmpPlayerName"); 
NavigationService.Navigate(new Uri("/ScoreInputDialog.xaml", UriKind.Relative)); 

注:OnNavigatedTo也將在用戶看到的頁面在第一時間或導航叫從「ScoreInputDialog.xaml」以外的頁面返回。但是,那麼「tmpPlayerName」值將不會被設置。

+0

感謝您的示例和解釋。它解決了我的問題。 – Mudasar

相關問題