2013-08-28 68 views
3

當我從我的應用程序點擊時,我需要ovveride窗口後退按鈕。我嘗試了下面的2個方法,但它不能在Windows Phone 8中工作?如何在windows phone 8中覆蓋windows back按鈕?

方法1)

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) 

      { 

      e.Cancel = true; 

      var result = MessageBox.Show("Do you want to exit?", "Attention!", 
             MessageBoxButton.OKCancel); 

     if (result == MessageBoxResult.OK) 
     { 
      // base.OnBackKeyPress(e); 
      return; 
     } 
     e.Cancel = true; 
    } 

方法2)

一)在XAML寫這個標題

BackKeyPress="MyBackKeyPress" 

b)以構造

BackKeyPress += OnBackKeyPress; 

c)中Initlize此並調用這個方法

private void MyBackKeyPress(object sender, System.ComponentModel.CancelEventArgs e) 
    { 
     e.Cancel = true; //tell system you have handled it 
     //you c 
    } 

這兩種方法都不起作用。當我點擊後退按鈕時,應用程序被摧毀,無法獲得後退控件。任何幫助?

回答

6

按照認證要求,不建議重寫後退按鈕 -

按應用程序的第一個屏幕中的後退按鈕必須關閉 應用程序。

http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh184840%28v=vs.105%29.aspx

你可以試試這個代碼

protected override void OnBackKeyPress(CancelEventArgs e) 
{ 
    if(MessageBox.Show("Are you sure you want to exit?","Confirm Exit?", 
          MessageBoxButton.OKCancel) != MessageBoxResult.OK) 
    { 
     e.Cancel = true; 

    } 
} 
+0

是的,我把代碼不在起始頁面。這不起作用。我正在使用模擬器進行測試。 – user1703145

+0

你有沒有例外?崩潰? – Anuraj

+0

應用正在退出,沒有發生任何異常,也沒有崩潰。 – user1703145

2

試試這個,這

第1步工作對我來說:在XAML

BackKeyPress="PhoneApplicationPage_BackKeyPress" 

步驟2:在C#

private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e) 
     { 
      MessageBoxResult mRes = MessageBox.Show("Would you like to exit?", "Exit", MessageBoxButton.OKCancel); 
      if (mRes == MessageBoxResult.OK) 
      { 
       NavigationService.GoBack(); 
      } 
      if (mRes == MessageBoxResult.Cancel) 
      { 
       e.Cancel = true; 
      } 
     } 
+0

它工作正常嗎? –

+0

我也一樣。但它不起作用。我把代碼中的斷點,也發現它沒有進入或沒有調用當我點擊返回按鈕的功能。 – user1703145

+0

是的,我從[鏈接] http://stackoverflow.com/questions/17397163/what-is-the-hype-around-the-windows-phone-8-back-button [鏈接]得到的解決方案...其問題涉及(5.2.4。3)上下文路徑..謝謝.. – user1703145

0

我試過相同。但它不起作用。我把代碼中的斷點,也發現它沒有進入或沒有調用當我點擊返回按鈕的功能。 - user1703145 45分鐘前

您還沒有忘記在XAML中綁定此事件?

<phone:PhoneApplicationPage ..... BackKeyPress="phoneApplicationPage_BackKeyPress"> 
+0

我已添加它,但沒有效果 – user1703145

+0

您是通過事件屬性手動還是自動添加它?可能會嘗試自動執行它,如果你手動完成它? – Cheese

+0

我嘗試了兩種方法。我在我點擊的同一頁面上提供了ovverride方法。這與導航或事件有任何關係。我導航到下一頁像這樣Page3 obj = new Page3(data.message_id); this.Content = obj; – user1703145

1

在你MyBackKeyPress方法,拋出一個新的異常關閉應用程序在運行,並返回到手機的菜單。我不知道這是否是實現這一目標的好方法,但這絕對可以解決問題。

private void MyBackKeyPress(object sender, System.ComponentModel.CancelEventArgs e) 
{ 
    throw new Exception(); 
} 

測試此模擬器/設備上,而不在Visual StudioDubugging,你會看到你的應用程序關閉。

相關問題