MessageBox in Windows Phone 8.1

本文关键字:Phone Windows in MessageBox | 更新日期: 2023-09-27 18:02:43

我想在硬件上按下后退按钮时向用户显示一个MessageBox,但是它根本不起作用。我尝试了这些变化,但我从来没有看到MessageBox:

    // VARIATION 1
    IAsyncResult mbResult = Microsoft.Xna.Framework.GamerServices.Guide.BeginShowMessageBox("Warning", "Are you sure you want to leave this page?",
    new string[] { "Yes", "No" }, 0, Microsoft.Xna.Framework.GamerServices.MessageBoxIcon.None, null, null);
    mbResult.AsyncWaitHandle.WaitOne();
    int? yesNo = Microsoft.Xna.Framework.GamerServices.Guide.EndShowMessageBox(mbResult);
    if (yesNo.HasValue)
    {
        if (yesNo.Value == 0)
        {
            // Yes pressed
        }
        else
        {
            // No pressed
        }
    }
    // VARIATION 2
    MessageBoxResult mbr = MessageBox.Show("Are you sure you want to leave this page?", "Warning", MessageBoxButton.OKCancel);
    if(mbr == MessageBoxResult.OK)
    {
        // OK pressed
    }
    else
    {
        // Cancel pressed
    }

如果我将e.Cancel = true写入OnBackKeyPress事件,那么我不能离开页面,因此代码正在执行,但我从未看到MessageBox:

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
    e.Cancel = true;
}

可能是什么问题,或者我做错了什么?

MessageBox in Windows Phone 8.1

我可以看到你的目标是Windows Phone 8.1 Silverlight,那么这个问题的答案仍然是实际的,如MSDN"

适用于:Windows Phone 8和Windows Phone Silverlight 8.1 | Windows Phone OS 7.1

在Windows Phone 8中,如果你在OnBackKeyPress(CancelEventArgs)或BackKeyPress事件的处理程序中调用Show,应用程序将退出。

在MSDN上也给出了解决方案。很快-运行您的messagebox。在Dispatcher上显示:

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
    e.Cancel = true;
    Deployment.Current.Dispatcher.BeginInvoke(() =>
    {
      MessageBoxResult mbr = MessageBox.Show("Are you sure you want to leave this page?", "Warning", MessageBoxButton.OKCancel);
      if(mbr == MessageBoxResult.OK)
      {   OK pressed  } 
      else
      {   Cancel pressed  }
    });
}

你可能已经解决了你的问题,但从它的外观,你的硬件后退按钮从未触发,并触发它的默认值

你需要在initialize组件下添加这个来让你的方法触发。

HardwareButtons.BackPressed += HardwareButtons_BackPressed;

试试这段代码,会有帮助的

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
    MessageBoxResult Exit = MessageBox.Show("Do You Want To Exit?", "Attention !!!", MessageBoxButton.OKCancel);
    if (Exit == MessageBoxResult.OK)
    {
        Application.Current.Terminate(); //Terminates App    
    }
    else if (Exit == MessageBoxResult.Cancel)
    {
        e.Cancel = true;
    }
}