【问题标题】:Uwp Conditional back navigation with a Message Dialog带有消息对话框的 Uwp 条件返回导航
【发布时间】:2021-02-12 11:05:31
【问题描述】:

我想询问用户他们是否确定要向后移动,并且只有在他们选择“是”时才向后移动,因为我正在使用消息对话框,但问题是当我按下返回按钮时它向后移动,然后弹出对话框询问我是否要向后移动。

我在 messageDialog.ShowAsync 执行后立即检查断点。

代码

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
    SystemNavigationManager.GetForCurrentView().BackRequested += SampleConditionalNavigation_BackRequested;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    base.OnNavigatedFrom(e);
    SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
    SystemNavigationManager.GetForCurrentView().BackRequested -= SampleConditionalNavigation_BackRequested;
}
private async void SampleConditionalNavigation_BackRequested(object sender, BackRequestedEventArgs e)
{
    e.Handled = true; // I have also tried setting it to false
    var messageDialog = new MessageDialog("Are you sure you want to move back?") { Title = "Confirmation" };
    // Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers
    messageDialog.Commands.Add(new UICommand("Yes"));
    messageDialog.Commands.Add(new UICommand("No"));

    // Set the command that will be invoked by default
    messageDialog.DefaultCommandIndex = 0;
    // Set the command to be invoked when escape is pressed
    messageDialog.CancelCommandIndex = 1;

    //ShowDialog
    var result = await messageDialog.ShowAsync();
    if (result.Label == "Yes")
    {
            var rootFrame = Window.Current.Content as Frame;
            if (rootFrame?.CanGoBack is true)
        {
                rootFrame?.GoBack();
        }
    }
}

更新 1

即使我注释了对话框显示自己页面仍然导航回来的代码,似乎 e.Handled = true 在这里几乎没用

【问题讨论】:

  • e.Handled = true 确实有效,当我在空白应用程序中测试时,您的代码也有效。

标签: c# xaml asynchronous uwp navigation


【解决方案1】:

此代码绝对正确且运行良好,问题是我的应用在 app.xaml.cs 中也有 BackRequested 事件,并且该事件正在执行并在此页面上的此方法之前返回能够执行。从 app.xaml.cs 中删除它解决了这个问题。

【讨论】:

    猜你喜欢
    • 2016-07-19
    • 1970-01-01
    • 2018-01-31
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多