c# - 如何在 OnNavigatingFromAsync 中显示模态对话框并取消导航

标签 c# win-universal-app template10

当使用Template 10时您可以通过重写 INavigable 方法 OnNavigatingFromAsync 并将 args.Cancel 设置为 true,让页面的 ViewModel 取消离开页面的导航,像这样:

public override Task OnNavigatingFromAsync(NavigatingEventArgs args)
{
    // some logic to determine if navigation should be canceled...
    args.Cancel = true;
    return Task.CompletedTask;
}

这工作得很好,但是如果我想向用户显示模式对话框(解释导航被取消的原因),我会将方法修改为:

public async override Task OnNavigatingFromAsync(NavigatingEventArgs args)
{
    args.Cancel = true;
    ContentDialog dlg = new ContentDialog()
    {
        Title = "Bad",
        Content = "no no no!",
        PrimaryButtonText = "OK",
        SecondaryButtonText = "NO"
    };
    await dlg.ShowAsync();           
}

这将显示对话框,但导航不会取消。就像 T10 忽略了 args.Cancel = true; 的设置。

我在这里做错了什么吗?我只想显示对话框然后阻止导航..

最佳答案

我在汉堡示例上尝试了模板 10 (1.1.4) 上的模态,效果完美。

对我来说,我认为您的错误出在方法“OnNavigatingFromAsync”上,看起来它最后缺少“return Task.CompletedTask”。

对我来说,当我单击应用程序中的后退键时,此代码会阻止应用程序返回:

 public override Task OnNavigatingFromAsync(NavigatingEventArgs args)
        {
            args.Cancel = true;

            ContentDialog dlg = new ContentDialog()
            {
                Title = "Bad",
                Content = "no no no!",
                PrimaryButtonText = "OK",
                SecondaryButtonText = "NO"
            };
            dlg.ShowAsync();

            return Task.CompletedTask;
        }

关于c# - 如何在 OnNavigatingFromAsync 中显示模态对话框并取消导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35561107/

相关文章:

mvvm - 在UWP中,只读的计算属性未在View中更新

c# - Atata 框架上的 Link 和 DelegateLink 有什么区别?

c# - 排除特定上下文的正则表达式匹配

javascript - 从通用共享应用程序访问类库

c# - 将事件绑定(bind)到属性的替代方法

xaml - ListView MVVM内TextBox上的UWP InvokeCommandAction

c# - 从主页绑定(bind)到 Template10 设置

c# - 无法使用 MySQLConnection 连接到 MySQL 数据库

c# - 检测游戏是否在安卓模拟器中运行

c# - 文本框选择颜色和选择括号颜色