我有一个UWP应用程序 - 该设计有一个" Back"屏幕内容中的按钮,我想用它来触发我的App.xaml.cs
文件中处理的系统导航事件。我当前的点击处理程序粘贴到需要它的每个文件:
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame.CanGoBack)
rootFrame.GoBack();
我如何触发后退事件,这会触发已经包含此代码的后台事件处理程序?
答案 0 :(得分:0)
在App.xaml.cs中,将其添加到OnLaunced(...):
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
...
if (rootFrame == null)
{
...
// Register a handler for BackRequested events
SystemNavigationManager.GetForCurrentView().BackRequested += this.OnBackRequested;
}
...
}
OnBackRequested(...)中的位置,也可以在App.xaml.cs中:
private void OnBackRequested(object sender, BackRequestedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame.CanGoBack)
{
e.Handled = true;
rootFrame.GoBack();
}
}
如果您实现任何自定义导航,这可以很容易地适用于支持多个帧,您还可以通过以下方式添加显示/隐藏后退按钮的全局处理:
public void UpdateBackButton(Frane frame)
{
bool canGoBack = (frame?.CanGoBack ?? false);
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = canGoBack
? AppViewBackButtonVisibility.Visible
: AppViewBackButtonVisibility.Collapsed;
}
您可以通过App.xaml.cs中的此类函数或自定义导航管理器以编程方式回调:
public bool TryGoBack(Frame frame)
{
bool handled = false;
if (frame?.CanGoBack ?? false)
{
handled = true;
frame.GoBack();
}
this.UpdateBackButton(frame);
return handled;
}