【发布时间】: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