Cancel navigation in Page.OnNavigatingFrom with MessageBox

I have a two-page WinRT application where the first goes to the second. I want to ask the user in OnNavigatingFromif he really wants to go to the second, through the message box. Canceling navigation is done by installing .Cancel=truefrom eventargs..., which I can do AFTER the end of the message window.

My problem is what MessageDialog.ShowAsyncis an asynchronous method.

1. Unable to execute .AsTask().Result... which causes a dead end, of course.

2. It is impossible to use awaitbecause OnNavigatingFrom- void, so turning on async causes the caller to return immediately when I wait ShowAsync().AsTask().Result.

+4
source share
2 answers

So, I found a way to do this. He based on these two answers:

Essentially, what you do is cancel by default, then you show your dialog box, and then if it’s normal for navigation, you set a flag that prevents you from setting the cancel to true, and then you go to the page.

In its simplest form, it looks like this.

bool _navigabile = false;
protected async override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
    if (!_navigabile)
    {
        e.Cancel = true;
        var result = true;// await MessageDialog.ShowAsync(/*...*/)

    if (result)
        {
            _navigabile = true;
            var current = Window.Current;
            var frame = current.Content as Frame;

            var ignore = current.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                        () => frame.Navigate(e.SourcePageType, e.Parameter));
        }
    }
}
+1
source

Cannot cancel navigation asynchronously from the OnNavigatingFrom event handler (NavigatingCancelEventArgs e).

, , .

var dialog          = new MessageDialog("Navigate away ?");
var okCommand       = new UICommand("OK");
var cancelCommand   = new UICommand("Cancel");
dialog.Commands.Add(okCommand);
dialog.Commands.Add(cancelCommand);

var result  = await dialog.ShowAsync();
if(result == okCommand)
{
    (Window.Current.Content as Frame).Navigate(typeof(BlankPage1));
}
0

All Articles