Thursday, June 21, 2012

Implementing Confirm on exit in Windows Phone

Close a WP7 application programatically? or Exiting a Windows Phone Application .

In this post I will show how to create a simple function for ask confirm on exit application.

Step 1. You need to create a function for clear navigation history:

private void ClearBackEntries()
{
    while (NavigationService.BackStack != null & NavigationService.BackStack.Count() > 0)
        NavigationService.RemoveBackEntry();
}

NOTE: in Markeplace there are many applications with an annoying problem when you try exit from main page: you have to navigate all visited pages. With this function you can solve the problem.

Step 2. You need to manage the phone BackKeyPress event in your MainPage.xaml

private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
{
    // TO DO
}
Step 3. Insert a MessageBox dialog and use stop back event when the user don't want exit the application
if (MessageBox.Show("Are you sure?", "Exit?", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
this.ClearBackEntries();
   else
e.Cancel = true;

No comments:

Post a Comment