We can write code to programatically handle the Back button of Windows Phone.
In .xaml file, add this code:
BackKeyPress="PhoneApplicationPage_BackKeyPress"
It should look like:
<phone:PhoneApplicationPage BackKeyPress="PhoneApplicationPage_BackKeyPress"
..//other attributes .. >
In the .cs file, write the function to handle the back key press as follows:
private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
{
MessageBoxResult mb = MessageBox.Show("Do you want to exit the page?", "Alert", MessageBoxButton.OKCancel);
if (mb == MessageBoxResult.OK)
{
if (NavigationService.CanGoBack)
{
while (NavigationService.RemoveBackEntry() != null)
{
NavigationService.RemoveBackEntry();
}
}
}
else
{
e.Cancel = true;
}
}
All the back entry elements in the stack are deleted after executing this code and the app will exit.