21

How would I handle the back button for windows mobile 10 and the back button for windows 10 tablet mode? I've been looking everywhere but can't find any examples for it.

shady
  • 1,076
  • 2
  • 13
  • 33

2 Answers2

29

This topic is one of the examples used in the Guide to Universal Windows Platform apps . I strongly suggest reading that when getting started with Universal apps.

For the button on the page header use Windows.UI.Core.SystemNavigationManager and set the AppViewBackButtonVisibility property to show or hide the button and handle the BackRequested event to perform the navigation.

Windows.UI.Core.SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
Windows.UI.Core.SystemNavigationManager.GetForCurrentView().BackRequested += (s,a) =>
{
    Debug.WriteLine("BackRequested");
    if (Frame.CanGoBack)
    {
        Frame.GoBack();
        a.Handled = true;
    }
}

You wire up the hardware back button the same as you do in Windows Phone 8.1, but you should check for the PhoneContract (or the individual class and method) to make sure it is there:

if (ApiInformation.IsApiContractPresent ("Windows.Phone.PhoneContract", 1, 0)) {  
    Windows.Phone.UI.Input.HardwareButtons.BackPressed += (s, a) =>
    {
        Debug.WriteLine("BackPressed");
        if (Frame.CanGoBack)
        {
            Frame.GoBack();
            a.Handled = true;
        }
    };
}
Rob Caplan - MSFT
  • 21,714
  • 3
  • 32
  • 54
  • Where is AppViewBackButtonVisibility supposed to be put? MainPage contstructor doesn't do anything for me nor the OnLaunched in App.xaml.cs – robertk Jun 03 '15 at 08:38
  • It goes on the title bar automatically :) – shady Jun 03 '15 at 15:22
  • 1
    Is there any way to customize the background color of the back button? – Michael Sabin Jun 29 '15 at 17:02
  • Maybe its better to check "ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))" because not every Phone get HardwareButtons like Lumia 630 etc. –  Jul 15 '15 at 12:47
  • Checking for the contract or for the type are equivalent here: if the contract is present then the class must be. The soft back button on the Lumia 630 still comes through the HardwareButtons class. – Rob Caplan - MSFT Jul 15 '15 at 23:53
  • I could only thay that MS in his sampels: https://github.com/Microsoft/Windows-universal-samples use "Windows.Phone.UI.Input.HardwareButtons". Maybe its better if there will be a Tablet with HardwareButtons or somthing else. –  Jul 16 '15 at 07:35
  • You're over thinking it. As I said in my answer, both ways will work here. – Rob Caplan - MSFT Jul 16 '15 at 14:52
  • it works in my case, just wonder if it is possible manually dispatch back event? – Thomas Lee Sep 22 '15 at 10:37
6

Add the following code to your App.xaml.cs and it will handle the navigation on desktop, tablet and mobile (I tested it on the mobile emulator) for better highlighted differences and explanation (Handling The Back Button In Windows 10 UWP Apps by JEFF PROSISE)

sealed partial class App : Application
{

    public App()
    {
        this.InitializeComponent();
        this.Suspending += OnSuspending;
    }

    protected override void OnLaunched(LaunchActivatedEventArgs e)
    {
        Frame rootFrame = Window.Current.Content as Frame;

        // Do not repeat app initialization when the Window already has content,
        // just ensure that the window is active
        if (rootFrame == 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 = 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;
        }

        if (rootFrame.Content == null)
        {
            // When the navigation stack isn't restored navigate to the first page,
            // configuring the new page by passing required information as a navigation
            // parameter
            rootFrame.Navigate(typeof(MainPage), e.Arguments);
        }

        // Ensure the current window is active
        Window.Current.Activate();
    }

    void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
    {
        throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
    }

    private void OnNavigated(object sender, NavigationEventArgs e)
    {
        // Each time a navigation event occurs, update the Back button's visibility
        SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
            ((Frame)sender).CanGoBack ?
            AppViewBackButtonVisibility.Visible :
            AppViewBackButtonVisibility.Collapsed;
    }

    private void OnSuspending(object sender, SuspendingEventArgs e)
    {
        var deferral = e.SuspendingOperation.GetDeferral();
        // TODO: Save application state and stop any background activity
        deferral.Complete();
    }

    private void OnBackRequested(object sender, BackRequestedEventArgs e)
    {
        Frame rootFrame = Window.Current.Content as Frame;

        if (rootFrame.CanGoBack)
        {
            e.Handled = true;
            rootFrame.GoBack();
        }
    }
}
Shehab Fawzy
  • 7,148
  • 1
  • 25
  • 18
  • I'm trying this on my Lumia 950 to hide the buttons along the button, back, home and search. It doesn't do anything and they are still there, any ideas why? – Nick Jan 18 '16 at 19:07
  • The answer is in regard to the special back button that appears on the top left and handling the hardware button that has a default behavior of exiting the app. it doesn't have anything to do with home and search buttons. – Shehab Fawzy Jan 19 '16 at 15:26
  • aah okay thanks, my bad. I found the info I wanted in the end. – Nick Jan 20 '16 at 18:53
  • i have an error, like a this picture: https://1drv.ms/i/s!Auqiv8Ukng7U7Q0yE5XjtLC-RX8A. How to handle it? – Rose Jul 21 '16 at 03:16