Developing for Modern Windows

Tips, tricks, and guides for developing on modern Windows platforms

Control the Windows Phone Back Button (Windows Phone Silverlight 7 / 8 / 8.1)

Note: This method for overriding the Windows Phone Back button is for Silverlight apps only.  Please see my other post on the Back button in Windows Phone 8.1 WinRT apps.

By default Windows Phone keeps pages on a ‘back stack’ and automatically navigates backwards through that stack (eventually exiting the app) when you press the hardware Back button. This is intuitive, but you may want to override the behaviour from time to time.

However, keep in mind that the expected behaviour – that pressing Back takes the user back a step – should be preserved (you’ll likely fail certification if it isn’t). Overriding the Back button is not intended to let you assign the Back button to random functions (e.g. pausing audio playback); you should override the Back button when doing so preserves the user experience in an intuitive, logical way. For example I have an app that uses popup windows to display content. If a popup window is displayed and the user presses Back, the window closes, but the page does not navigate backwards.

Overriding the Back Button

To override the Back button you need a very simple method in your page’s code behind.
Firstly, add the ComponentModel namespace to your page:


using System.ComponentModel;

Then add this method:


protected override void OnBackKeyPress(CancelEventArgs e)
{
    // put any code you like here
MessageBox.Show("You pressed the Back button");
e.Cancel = true;                       
}

This little method overrides the default Back button behaviour with whatever you put inside it. There is one important line of code I’ve added in the above method:


e.Cancel = true;

Setting e.Cancel to true tells the OS to cancel the default Back button behaviour (i.e. navigating to the previous page). If you leave that line out your method would run, and then the phone would also navigate backwards (which may be the behaviour you want).

Tags: , , ,

2 Responses to “Control the Windows Phone Back Button (Windows Phone Silverlight 7 / 8 / 8.1)”

  1. […] 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. […]

  2. […] this technique is for Windows Phone 8.1 WinRT apps only. Please see this post for previous versions of Windows Phone (including Windows Phone 8.1 Silverlight […]

Leave a Reply

Your email address will not be published.