Intercepting and Overriding the Back Button in Windows Phone 8 Apps

If you want to prevent the default action happening when a user presses the back button on a Windows Phone you can override the OnBackKeyPress method in your page. To prevent the default back behaviour (e.g. navigating to the previous app page) you can set the Cancel property of the CancelEventArgs to true.

The following code shows how to prevent the back button from navigating to the previous page if a UI element called “ShareChoices” is visible:

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
    if (ShareChoices.Visibility == Visibility.Visible)
    {
        HideShareChoices();
        e.Cancel = true;
    }
}

When deciding to override (and cancel) the default back button behaviour, be sure that it’s sensible and intuitive to the user. Incorrect use may result in certification failure.

One use that I’ve seen is in data entry apps. On the main page, the back is intercepted and if there are unsaved data entry changes an “are you sure” dialog is displayed. You shouldn’t do this “are you sure you want to exit app” on apps where there is no loss of data if a user exits. In these cases this kind of “exit prompt” will be annoying and pointless to the user.

Pingbacks and trackbacks (2)+

Add comment

Loading