2012-06-16 120 views
1

當用戶點擊後退按鈕後點擊「取消」按鈕時,如何阻止我的應用程序返回?WP7停止頁面導航/返回

 protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) 
    { 
     var buttonInfo = MessageBox.Show("Are you sure you want to exit?", "Exit", MessageBoxButton.OKCancel); 
     if (buttonInfo == MessageBoxResult.OK) 
     { 
      this.NavigationService.GoBack(); 
     } 
     else 
     { 
      //How to stop page from navigating 
     } 
    } 
+0

在這樣小心,因爲這取決於使用,有可能倒塌的認證要求的犯規;特別是[第5.2.4節](http://msdn.microsoft.com/en-us/library/hh184840%28v=vs.92%29.aspx) –

回答

2

使用CancelEventArgs取消操作,屬性Cancel

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) 
{ 
    // If the event has already been cancelled, do nothing 
    if(e.Cancel) 
     return; 

    var buttonInfo = MessageBox.Show("Are you sure you want to exit?", "Exit", MessageBoxButton.OKCancel); 
    if (buttonInfo == MessageBoxResult.OK) 
    { 
     this.NavigationService.GoBack(); 
    } 
    else 
    { 
     //Stop page from navigating 
     e.Cancel = true; 
    } 
} 
+0

完美。非常感謝你! – Subby

+0

很高興它適合你。你還應該檢查even是否已經被取消,在這種情況下什麼也不做。 –

1

多一點..

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) 
    { 
     if (e.Cancel) 
      return; 

     var buttonInfo = MessageBox.Show("Are you sure you want to exit?", "Exit", MessageBoxButton.OKCancel); 
     if (buttonInfo == MessageBoxResult.OK) 
     { 
      **//this line may useful if you are in the very first page of your app** 
      if (this.NavigationService.CanGoBack) 
      { 
       this.NavigationService.GoBack(); 
      } 
     } 
     else 
     { 
      //Stop page from navigating 
      e.Cancel = true; 
     } 
    }