0
votes

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.

1
You need to intercept the back button press (there's an event for that). In OnNavigatedFrom it's already too lateKevin Gosse
I did intercept the back button press, however I cannot seem to be able to disable it... I'm using the HardwareButtons_BackPressed event, but I cannot seem to disable it's functionality.Keran
@Keran Try to set e.Handeled = true if you need to disable back button further process.Romasz
I specified e.Handled = true, however it still goes back. And if the messagebox questions is there, it gets stuck anyway. (Perhaps I should not use NavigationHelper?) This is my HardwareButtonsOnBackPressed event: private async void HardwareButtonsOnBackPressed(object sender, BackPressedEventArgs backPressedEventArgs) { backPressedEventArgs.Handled = true; } If there are so many problems with this, how other people in their apps make the MessageBox with question on back button pressed? (For WP 8.1 Runtime)Keran

1 Answers

1
votes

You can use following event .

HardwareButtons.BackPressed += HardwareButtons_BackPressed;



    void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
    {

    }