Wednesday, September 08, 2010

Performing Back Navigation w/out adding a page to the Back Stack in WP7

In a previous post (here) I wrote about how you can catch the back button action on WP7.  In this post I will explain how you can use the NavigationService provider in WP7 to correctly navigate back to a calling page in order to remove a existing page from the back stack in order to prevent the user from going back to the page.
Below is a pretty simple sample work flow.  You go from the home page, to a second page and then back to the home page.  The item we want to discuss is how we go from the second page back to the home page.
One way to perform navigation is to utilize the NavigationService and simply use Navigate and provide the URI to navigate to.  See blow for an example
NavigationService.Navigate( new Uri( "/MainPage.xaml", UriKind.RelativeOrAbsolute ) );
The issue with this approach is that you are now creating a new page on the Navigation Stack.  This means that if the user hits the back button on the phone they will be routed back to the SecondPage.xaml.
Option #2 – Navigate from the SecondPage.xaml to the MainPage.xaml using the NavigationService.GoBack()
When you use the NavigationService provider to perform back navigation using the GoBack() you do not add a new page to the stack, this is a GOOD thing.  This means that if the user hits the back button on the MainPage.xaml they will NOT be routed back to the SecondPage.xaml again.
if ( NavigationService.CanGoBack )
{
   NavigationService.GoBack();
}
Read more: Derik Whittaker