屏幕后退按钮上的UWP - 如何触发系统后退事件?

问题描述:

我有一个UWP应用程序 - 设计在屏幕内容中有一个“返回”按钮,我想用它来触发在我的App.xaml.cs文件中处理的系统导航事件。我目前的点击处理程序,粘贴到需要它的每个文件:屏幕后退按钮上的UWP - 如何触发系统后退事件?

Frame rootFrame = Window.Current.Content as Frame; 
if (rootFrame.CanGoBack) 
    rootFrame.GoBack(); 

我怎么会代替触发回事件,将触发已经包含这个代码后面的事件处理程序?

+1

你已经采取了看样板10.电线了所有该锅炉板代码您。 –

在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; 
} 
+0

我已经拥有了所有这些 - 我想要做的就是从应用程序的内容区域中的“HyperlinkBut​​ton”中激发相同的'SystemNavigationManager.GetForCurrentView()。BackRequested'。 – Iiridayn

+0

查看可以在HyperlinkBut​​ton的事件处理程序中调用的TryGoBack函数的更新解决方案。 –

+0

你的编辑是我的问题的重复,但更明确地说。我在每个页面代码后面都有一个'TryGoBack'类方法,它需要它。 – Iiridayn