如何在Windows Phone 8中覆盖窗口后退按钮?

当我从我的应用程序点击时,我需要将窗口后退按钮。我尝试了下面的方法,但它在Windows Phone 8中不起作用?

方法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)

a)在xaml标题中写道

 BackKeyPress="MyBackKeyPress" 

b)在构造函数中初始化它

  BackKeyPress += OnBackKeyPress; 

c)并调用此方法

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

这两种方法都不起作用。 当我点击后退按钮时,应用程序被破坏,无法控制后门按钮。 有帮助吗?

根据认证要求,不建议覆盖后退按钮 –

从应用程序的第一个屏幕按“后退”按钮必须关闭该应用程序。

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

试试这个,对我有用

第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; } } 

MyBackKeyPress方法中,抛出一个新的exception以在运行时关闭应用程序并返回到手机的菜单。 我不知道这是否是实现它的好方法,但这肯定解决了这个问题。

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

Visual Studio没有Dubugging模拟器/设备上进行Dubugging ,您将看到您的应用程序关闭。

我也试过了。 但它不起作用。 我把断点放在代码中,并且当我点击后退按钮时也发现它没有进入或没有调用该函数。 – 用户1703145 45分钟前

你有没有忘记在XAML中绑定这个事件?