Handling system and app back button

This question came up a few times recently. How can a UWP app handle navigation with continuum for tablets. This is the setting at the bottom of Action Center that allows you to switch between tablet (touch) and PC mode (mouse).

When the system is in tablet mode, a back button appears on the left in the task bar. However, if the app is in PC mode, the app might need to have its own back button. You might not want both. This means that your app:

1. Needs to detect whether it is in tablet or pc-mode

2. If in tablet mode, don't show a back button since the system already has one in the taskbar

3. If in PC mode, show the back button (if there is something on the back stack.)

In order to detect 1) you should use this:

UIViewSettings.GetForCurrentView().UserInteractionMode == UserInteractionMode.Mouse;//or Touch

Mouse indicates PC mode; Touch indicates tablet mode. Depending on the outcome, you can hide or show your app's back button in the title bar by setting AppViewBackButtonVisibility to Visible or Collapsed.

You then need to handle one event for both

SystemNavigationManager.GetForCurrentView().BackRequested

And don't forget to set BackRequestedEventArgs.Handled to true if you're handling the back navigation. Otherwise the system will also navigate away from your app.

Complete code:

protected override void OnNavigatedTo(NavigationEventArgs e)

{

    SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =

        (UIViewSettings.GetForCurrentView().UserInteractionMode == UserInteractionMode.Mouse) ?

        AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed;

 

    SystemNavigationManager.GetForCurrentView().BackRequested += SettingsPage_BackRequested;

}

 

protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)

{

    SystemNavigationManager.GetForCurrentView().BackRequested -= SettingsPage_BackRequested;

}

 

private void SettingsPage_BackRequested(object sender, BackRequestedEventArgs e)

{

    App.RootFrame.Navigate(typeof(MainPage));

    e.Handled = true;

}