简体   繁体   中英

Windows Phone 8.1 runtime show message box on OnNavigatedFrom (back button)

I have been fighting with this for a while... I'm using Windows Phone 8.1 Runtime (not silverlight) and I have the following code:

    protected override void OnNavigatedFrom(NavigationEventArgs e)
    {
        if (!ExitWithoutSave().Result) return;
        this.navigationHelper.OnNavigatedFrom(e);
    }

    private async Task<bool> ExitWithoutSave()
    {
        MessageDialog dialog = new MessageDialog("There are unsaved changes, are you sure you wish to leave?", "Unsaved changes");
        dialog.Commands.Clear();
        dialog.Commands.Add(new Windows.UI.Popups.UICommand("Yes") { Id = 0 });
        dialog.Commands.Add(new Windows.UI.Popups.UICommand("No") { Id = 1 });

        dialog.DefaultCommandIndex = 0;
        dialog.CancelCommandIndex = 1;

        var result = await dialog.ShowAsync();
        if (result.Label == "No")
        {
            canceled = true;
        }

        return canceled;
    }

Basically, I want to ask the user if he wishes to leave without saving, if he says no, then I want to block this functionality.

The problem is, if there's an await during the execution of the OnNavigatedFrom, Windows phone thinks the app has broken and the UI gets blocked.

Is there any way to correctly show a message box on pressing the back button? If not, is it possible to disable the back button entirely for this page?

Thanks, Keran

Edit 15-11-2015: Just wanted to bump this post. I had no luck using HardwareButton events together with Navigation Helper, MessageBoxes still don't work. I can't even cancel the back button press. So I wanted to renew my question: What is the best way to create a confirm message box on back button press on Windows Phone 8.1 Runtime? F. e. message: "You have unsaved changes, do you wish to exit?": Yes / No.

You can use following event .

HardwareButtons.BackPressed += HardwareButtons_BackPressed;



    void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
    {

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM