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