[UWP][C#] 覆盖 Appx.cs 中设置的 backpress 导航

[UWP][C#] Override backpress Navigation set in Appx.cs

有点卡在这里。我有一个 splitview 应用程序,当按下驻留在 Appx.cs.

中的后退键时,它具有向后导航的事件

我想在 splitviews 内容页面内导航的页面之一中定义不同的操作(例如,当某个元素可见时关闭该元素)但是应用程序始终遵循 [=38 中设置的事件=],并忽略页面中加载到内容框架中的事件。这是 appx.cs 中的代码:

protected async override void OnLaunched(LaunchActivatedEventArgs e)
{
    // Do not repeat app initialization when the Window already has content,
    // just ensure that the window is active
    if (Window.Current.Content == null)
    {
        // Create a Frame to act as the navigation context and navigate to the first page
        _rootFrame = new Frame();
        _rootFrame.NavigationFailed += OnNavigationFailed;
        _rootFrame.Navigated += OnNavigated;

        if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
        {
            //TODO: Load state from previously suspended application
        }

        // Place the frame in the current Window
        Window.Current.Content = new MainPage(_rootFrame);

        // Register a handler for BackRequested events and set the
        // visibility of the Back button
        SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;

        SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
            _rootFrame.CanGoBack ?
            AppViewBackButtonVisibility.Visible :
            AppViewBackButtonVisibility.Collapsed;
    }
}

private void OnBackRequested(object sender, BackRequestedEventArgs e)
{
    if (_rootFrame != null && _rootFrame.CanGoBack)
    {
        e.Handled = true;
        _rootFrame.GoBack();

    }
}

这是加载到 splitviews 内容窗格的其中一个页面中的代码:

public CalcOutputPage()
{
    this.InitializeComponent();


    // add page specific handling of back navigation when entering this page
    SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
}

// page specific back button navigation
private void OnBackRequested(object sender, BackRequestedEventArgs e)
{

    if (MobileStackPanel.Visibility == Visibility.Visible)
    {
       MobileStackPanel.Visibility = Visibility.Collapsed;
        e.Handled = true;
    }
    else
    {
        e.Handled = false;
    }
}

但这不起作用。如果它是导航堆栈中加载的第一个页面,它会工作,但在所有其他时间,应用程序遵循 appx.cs

中的导航说明

所以澄清一下:

如有任何帮助,我们将不胜感激。我正在失去理智试图让它工作:P

事件处理程序的触发顺序与它们添加的顺序相同,所以这边运气不好。一种选择是制作您自己的活动,包装原始活动。在 App.xaml.cs:

public event EventHandler<BackRequestedEventArgs> BackRequested;

private void OnBackRequested(object sender, BackRequestedEventArgs e)
{
    // Raise child event
    var eventHandler = this.BackRequested;

    if (eventHandler != null)
    {
        eventHandler(sender, e);
    }

    if (!e.Handled)
    {
        if (_rootFrame != null && _rootFrame.CanGoBack)
        {
            e.Handled = true;
            _rootFrame.GoBack();

        }
    }
}

然后在您的页面中,订阅子事件而不是主要事件:

((App)(App.Current)).BackRequested += OnBackRequested;

确保在离开页面时取消订阅事件,否则可能会导致内存泄漏。