Control the Windows Phone 8.1 WinRT Back Button

Note: this technique is for Windows Phone 8.1 WinRT apps only. For previous versions of Windows Phone (including Windows Phone 8.1 Silverlight apps) see my previous post. This post shows how to intercept the Back button in Windows Phone 8.1 WinRT apps. You should have a good reason for doing this (see the previous post linked in the not above for details) or you may fail certification (or have an app that users find counter-intuitive).

App Templates and Navigation

WinRT apps have a great NavigationHelper class built in (except for the Blank App template). NavigationHelper does what you’d guess: it automates navigation, including the Back button behaviour. If your page uses NavigationHelper you need to modify NavigationHelper’s class a tiny bit. If you aren’t using it (e.g. you used the Blank App template and handle all navigation yourself) you can skip this step.

Modify NavigationHelper

Open NavigationHelper.cs (it will be in the Common folder) and replace the HardwareButtons_BackPressed method with the following:

private void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
{
    if (this.GoBackCommand.CanExecute(null) && !e.Handled)
    {
        e.Handled = true;
        this.GoBackCommand.Execute(null);
    }
}

All we’ve done here is add ” && !e.Handled” to that if statement. This changes NavigationHelper to only navigate backwards if the Back button press has not been handled elsewhere first. This is because we want the option to override the Back button completely.

Add a Namespace

Add the following namespace to your page:

using Windows.Phone.UI.Input;

Add the Handler

Add the handler to the page’s constructor method (e.g. public MainPage()):

HardwareButtons.BackPressed += OnBackPressed;

This tells your page to execute a method called OnBackPressed when the Back button is pressed.

Add the Overriding Code

You’ve told the page to call OnBackPressed when the Back button is pressed, so now you need to create that method. What goes in here is really up to you. You can close a popup, navigate to a specific page, etc.

private async void OnBackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
{         
    e.Handled = true;
    // add your own code here to run when Back is pressed
}

That single line “e.Handled = true” is important. The e.Handled state tells the OS if the Back button press has been dealt with (“handled”). When you set this to true the OS considers the matter dealt with; if you leave it (i.e. as false) the OS will still continue with the normal Back button behaviour after running your method (i.e. your method would run, and then the default backwards navigation would happen).