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.
Option #1 – Navigate from the SecondPage.xaml to the MainPage.xaml using NaviagationService.Navigate()
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 )
There is ONE potential issue with using the .GoBack() feature and that is that if you are not 100% sure of the page you were coming from you may actually be routed back to another page or even another application.
As you can see you can use the NavigationService provider to your advantage w/ little effort.
Till next time.
09-03-2010 6:39 PM