Custom MessageBox for exit in Windows Phone

六眼飞鱼酱① 提交于 2019-12-25 04:19:14

问题


I am showing a message box if a user taps "back" at the main page of a game application.

The usual solution

MessageBoxResult res = MessageBox.Show(txt, cap, MessageBoxButton.OKCancel);
    if (res == MessageBoxResult.OK)
    {
        e.Cancel = false;
        return;
    }

doesn't work for me, because I need those buttons to be localized not with a phone's localization but using app's selected language (i.e. if user's phone has english locale and he has set an app's language to be french, the buttons should be "Oui" and "Non" instead of default "OK" and "Cancel").

I have tried the following approach and it works visually:

protected override void OnBackKeyPress(CancelEventArgs e)
{
    //some conditions
    e.Cancel = true;
    string quitText = DeviceWrapper.Localize("QUIT_TEXT");
    string quitCaption = DeviceWrapper.Localize("QUIT_CAPTION");
    string quitOk = DeviceWrapper.Localize("DISMISS");
    string quitCancel = DeviceWrapper.Localize("MESSAGEBOX_CANCEL");
    Microsoft.Xna.Framework.GamerServices.Guide.BeginShowMessageBox(
        quitCaption, 
        quitText,
        new List<string> { quitOk, quitCancel }, 
        0, 
        Microsoft.Xna.Framework.GamerServices.MessageBoxIcon.Error,
        asyncResult =>
        {
            int? returned = Microsoft.Xna.Framework.GamerServices.Guide.EndShowMessageBox(asyncResult);
            if (returned.Value == 0) //first option = OK = quit the game
            {
                e.Cancel = false;
                return;
            }
        }, 
        null);
    //some more features
}

but it doesn't quit an application.

Which approach should I use? I am not to use "Terminate" because it's a fairly big app and it's not good to quit it that way.


回答1:


It doesn't quit because BeginShowMessageBox() is asynchronous. It means that call will return immediatly and because you set e.Cancel to true then application won't ever close (when your event handler will be executed calling method ended without quitting).

Just wait user closes the dialog to set e.Cancel to proper value (omitting AsyncCallback parameter). First remove callback:

IAsyncResult asyncResult = Guide.BeginShowMessageBox(
    quitCaption, quitText, new List<string> { quitOk, quitCancel }, 
    0, MessageBoxIcon.Error, null, null);

Then wait for dialog to be closed:

asyncResult.AsyncWaitHandle.WaitOne();

Finally you can check its return value (as you did in your original callback):

int? result = Guide.EndShowMessageBox(asyncResult);
if (result.HasValue && result.Value == 0)
    e.Cancel = false;


来源:https://stackoverflow.com/questions/24866404/custom-messagebox-for-exit-in-windows-phone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!