0

I want to ask for confirmation if the user wants to leave the page when the Back button (hardware or AppViewBackButton) is pressed using the following code in my App.xaml.cs

protected override void OnLaunched(LaunchActivatedEventArgs e)
{
  ...
      SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
  ...
}

Private async void OnBackRequested(object sender, BackRequestedEventArgs e)
{
    Frame rootFrame = Window.Current.Content as Frame;

    if (rootFrame.Content.GetType() == typeof(GamePage))
    {
        var op = await ShowAsync("Do you want to exit?", "Exit?");

        if (op == MessageBoxResult.OK)
        {

            rootFrame.GoBack();
            e.Handled = true;
        }
    }
    else
    {
        if (rootFrame.CanGoBack)
        {
            e.Handled = true;
            rootFrame.GoBack();
        }
    }
}

public async Task<MessageBoxResult> ShowAsync(string messageBoxText, string caption)
{
    MessageBoxResult result = MessageBoxResult.None;

    MessageDialog md = new MessageDialog(messageBoxText, caption);
    md.Commands.Add(new UICommand("OK",
         new UICommandInvokedHandler((cmd) => result = MessageBoxResult.OK)));


    md.Commands.Add(new UICommand("Cancel",
        new UICommandInvokedHandler((cmd) => result = MessageBoxResult.Cancel)));
    md.CancelCommandIndex = (uint)md.Commands.Count - 1;


    var op = await md.ShowAsync();

    return result;
}

The problem is var op = await md.ShowAsync(); does not await the result. The app showed the dialog briefly and without waiting for any input, just close the app.

I do not have my Windows 10 Mobile device to test at the moment so I am testing with the emulator. Is the problem with the emulator or the code?

This code works fine on my desktop though.

PutraKg
  • 2,226
  • 3
  • 31
  • 60
  • 2
    You need to set Handled to true before you await. Remember that awaiting causes the event handler to return, and the rest of the handler runs as an asynchronous task. – Raymond Chen Aug 03 '16 at 13:53
  • @RaymondChen Ah why I didn't think of that. For completeness sake, if you post an answer I will accept it. However why does it work on the desktop though? – PutraKg Aug 03 '16 at 13:57
  • Go ahead and post your answer once you've verified it to your satisfaction. I don't know why it works differently on desktop. My guess is that desktop and phone have different app switching models, so it just works on desktop by accident. – Raymond Chen Aug 03 '16 at 14:02

0 Answers0