문제

I want to show a MessageBox to the user when the back button has been pressed on the hardware, but it's simply doesn't work. I tried these variations, but I never see the 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
    }

If I write e.Cancel = true to the OnBackKeyPress event then I can't leave the page, so the code is executing, but I never see the MessageBox:

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

What can be the problem, or what I'm doing wrong?

도움이 되었습니까?

해결책

As I can see you are targeting Windows Phone 8.1 Silverlight, then answer to this question is still actual, as at MSDN"

Applies to: Windows Phone 8 and Windows Phone Silverlight 8.1 | Windows Phone OS 7.1

In Windows Phone 8, if you call Show in OnBackKeyPress(CancelEventArgs) or a handler for the BackKeyPress event, the app will exit.

The solution is also given at MSDN. Shortly - run your Messeagebox.Show on 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  }
    });
}

다른 팁

You may have solved your problem already but from the looks of it your hardwareback button never fired and was triggering it's default.

you need to add this under initialize component to get your method to fire.

HardwareButtons.BackPressed += HardwareButtons_BackPressed;

try this code it will help

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;
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top