e.Cancel 在 UWP 中等待异步对话后无法设置

e.Cancel cannot be set after awaiting async dialog in UWP

这适用于 Windows 10 UWP 应用。当用户试图离开页面时,我想让用户确认他是否想要保存当前数据。

我已经覆盖了 OnNavigatingFrom,如下所示。但是,在异步 MessageDialog 之后,设置 e.Cancel=false 不起作用。即使稍后将 e.Cancel 设置为 false,该页面仍停留在当前页面上。请帮忙!

protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)

{
    e.Cancel = true; //if I don't put this at the top, the page navigates right away

    var yesCommand = new UICommand("Yes", async cmd => {

        try
        {
            await SaveWorkshetItem(false);
            e.Cancel = false;
        }
        catch (Exception ex)
        {
            await new MessageDialog("Error saving Worksheet Item. Please contact you administrator." + ex.Message + Environment.NewLine + ex.StackTrace).ShowAsync();
        }

    });

    var noCommand = new UICommand("No", cmd => { e.Cancel = false; });

    var cancelCommand = new UICommand("Cancel", cmd => { e.Cancel = true;  });

    var dialog = new MessageDialog("Do you want to save the current item before navigating away?");
    dialog.Options = MessageDialogOptions.None;
    dialog.Commands.Add(yesCommand);

    dialog.Commands.Add(noCommand);
    dialog.Commands.Add(cancelCommand);

    await dialog.ShowAsync();

    base.OnNavigatingFrom(e);

}

为了简化这一点,即使我在示例 MessageDialog.

之后改回 e.Cancel=false,下面的代码也会导致页面永远不会离开
protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)

{
    e.Cancel = true; //if I don't put this at the top, the page navigates right away

    await new MessageDialog("Do you want to save the current item before navigating away?").ShowAsync();

    e.Cancel = false;  //unconditionally setting this back to false and it still won't leave the page

    base.OnNavigatingFrom(e);
}

要自己处理导航,请设置 Cancel=true(正如您已经设置的那样),然后打开对话框以获取用户输入。了解用户的选择后,如果用户决定允许进行导航,则使用导航 API(例如 Frame.GoBack)执行所需的导航(基于 e.NavigationMode)。

这是一些基本的示例代码:

private bool isNavigationConfirmed = false;
protected async override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
    base.OnNavigatingFrom(e);
    if (isNavigationConfirmed)
    {
        isNavigationConfirmed = false;
        return;
    }
    e.Cancel = true;

    var noCommand = new UICommand("No", cmd => { });
    var yesCommand = new UICommand("Yes", cmd =>
    {
        if (e.NavigationMode == NavigationMode.Back)
        {
            Frame.GoBack();
        }
        else
        {
            isNavigationConfirmed = true;
            Frame.Navigate(e.SourcePageType);
        }
    });

    var dialog = new MessageDialog("Do you want to allow navigation?");
    dialog.Options = MessageDialogOptions.None;
    dialog.Commands.Add(yesCommand);
    dialog.Commands.Add(noCommand);
    await dialog.ShowAsync();
}