在MessageDialog的UICommand中执行页面导航失败的问题排查
解决MessageDialog中UICommand触发页面导航失败的问题
我刚碰到过类似的坑,你这个问题的核心根本不是UI线程的问题——而是你自己在页面的导航拦截逻辑里,把导航操作给硬生生拦下来了!
问题还原
你的场景是用户点击MessageDialog里的"No, I Decline"按钮时,要跳转到LoginPage,最初的实现代码是这样的:
var decline = new UICommand("No, I Decline", async command => { await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { (Window.Current.Content as Frame).Navigate(typeof(LoginPage)); }); }); commands.Add(decline);
而且你还封装了ShowDialogue方法,确保弹窗在UI线程执行:
public static async void ShowDialogue(string message, string title, IEnumerable<UICommand> commands) { var Dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher; await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { var dialog = new MessageDialog(message, title); foreach (var command in commands) { dialog.Commands.Add(command); } dialog.DefaultCommandIndex = 0; dialog.CancelCommandIndex = 1; await dialog.ShowAsync(); }); }
找到的问题根源
最后你自己也排查出来了,问题出在页面重写的OnNavigatingFrom方法里:
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { if (allowToLeavePage == false) { e.Cancel = true; return; } displayRequest.RequestRelease(); }
这段代码会在页面准备导航离开时检查allowToLeavePage的状态,如果是false就直接取消导航操作——这就是为什么你的导航代码看似执行了,但页面根本没跳转的原因!
修复方案
解决起来很简单,只需要在触发导航前,把allowToLeavePage设为true,让导航能通过拦截逻辑:
修改后的UICommand代码:
var decline = new UICommand("No, I Decline", async command => { // 先解除导航拦截,允许页面离开 allowToLeavePage = true; await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { (Window.Current.Content as Frame).Navigate(typeof(LoginPage)); }); }); commands.Add(decline);
这样一来,当导航触发时,OnNavigatingFrom里的检查就会通过,不会取消导航,页面就能正常跳转到LoginPage了。
内容的提问来源于stack exchange,提问作者visc
相关产品推荐
相关产品推荐

