我有Prism和AppShell的UWP应用.
我想在通过BackButton退出之前添加确认对话框.
我尝试了这个:
protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args)
{
...
SystemNavigationManager.GetForCurrentView().BackRequested += App_BackRequested;
...
}
private void App_BackRequested(object sender, BackRequestedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null)
{
return;
}
if (rootFrame.CanGoBack && e.Handled == false)
{
<add confirm dialog here>
e.Handled = true;
}
}
但是rootFrame始终为null,并且如果历史记录堆栈为空,并且我按下了BackButton应用,即使执行此操作,也会关闭:
private void App_BackRequested(object sender, BackRequestedEventArgs e)
{
e.Handled = true;
}
我也尝试过
HardwareButtons.BackPressed += App_BackRequested;
这也无济于事.
解决方法:
尝试将以下这些行添加到OnLaunchApplicationAsync方法
protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args)
{
//......
DeviceGestureService.GoBackRequested += (s, e) =>
{
e.Handled = true;
e.Cancel = true;
if (NavigationService.CanGoBack())
{
NavigationService.GoBack();
}
else
{
// PUT YOUR LOGIC HERE (Confirmation dialog before exit)
Application.Current.Exit();
}
};
//......
}