Navigation 101–Cancelling Navigation

Windows Phone From Scratch #32

 

Let’s go back and look at the fundamentals of Navigation and how you can exert greater control as you navigate from page to page in your Windows Phone application.

Simple navigation, say from one page to the next, can be accomplished by calling on the NavigationService’s Navigate method, passing in the URI of the page you wish to navigate to.

 void GoToPage2_Click( object sender, 
                       RoutedEventArgs e )
 {
    NavigationService.Navigate( 
         new Uri( "/Page2.xaml", UriKind.Relative ) );
 }

 

There are a number of Navigating events that are raised as you move from one page to another, but the Phone Application Page makes these available as virtual methods; handling the registration and de-registration of the events for you.

The four overrideable methods are

  • OnNavigatingFrom
  • OnNavigatedFrom
  • OnNavigatedTo
  • OnFragmentNavigation

The first two are interesting; the former is called when you are about to navigate from one page to another, the latter just after navigation is completed.  You can intercept the process of navigating from one page to another by overriding OnNavigatingFrom.

To see this at work, create a new application. On MainPage.xaml add a button in the center of the content area named GoToPage2.  Add a second page, name it Page2.xaml and in the middle of its content area add a button named BackToPage1

Next, add navigation from one page to the other as shown above.  Run the application and prove to yourself that you can navigate from page 1 to page 2. Admittedly animation would help make the transitions less jarring, but we’ll come back to that in a future posting.

Next, on page 2, override the OnNavigatingFrom method as shown here,

protected override void OnNavigatingFrom( 
 System.Windows.Navigation.NavigatingCancelEventArgs e)
{

   if ( MessageBox.Show(
      "Really change pages?", 
      "Really??", 
      MessageBoxButton.OKCancel) 
         != MessageBoxResult.OK )
   {
      e.Cancel = true;            
   }

   base.OnNavigatingFrom( e );
}

 

The essence of this method is to intercept the navigation and to display a message box confirming that navigating is what the user wishes to do. If not, e.Cancel is set to true, and the navigation will be aborted.

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Microsoft MVP.
This entry was posted in Patterns & Skills. Bookmark the permalink.

One Response to Navigation 101–Cancelling Navigation

Comments are closed.