27 July 2012

Windows Phone 7.5 - Home button Navigation and Exit Confirmation

While developing a windows phone application, the one which involves navigation to various pages starting from something called as a homepage would quickly become annoying. You will find yourself in deeper pages and as a means on coming back to the home page, you will keep pressing the back button so many times it will exit you out of the application.

There are couple of problems associated with this. The user is forced to keep in mind how deep he has in the navigation page. The other main problem is he will not have patience to wait to go to the home page and pressing the back button on the first page will obviously throw you. This is because the navigation details are stored in a stack.

It is always nice to provide a home button to the end user on all the pages so that on click of them will take it to the home. Also, you can always have a confirmation dialogue fired while exiting the application. First problem first.

This code armed with a Home button will do the job cleanly for you.

private void Home_Click(object sender, System.Windows.RoutedEventArgs e)
    int depth = NavigationService.BackStack.Count();
    for (int i = 0; i < depth - 1; i++) { NavigationService.RemoveBackEntry(); }

The funda here is it will empty all the stack and will call the back action of the navigation service just once making sure that the next back() will empty the stack and will make you quit.

As I told before adding this code to the MainPage.xaml.cs will show a confirmation popup while quitting the application so that user only deliberately quits but not accidentally.

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
    if (MessageBox.Show("Are you sure you want to exit?", "Exit?", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
        e.Cancel = true;

These techniques are very simple and subtle but will improve the usability of your application by leaps and bounds.


No comments: