Removing the BackStack Entry in Windows Phone

A reader correctly complained about my posting on Sending Messages Between Pages that the “dialog” box I had created was in the BackStack.  If you were to go through the dialog and then later hit the hardware back-key you would be “dragged through” the dialog box on your way back through the pages.  Fail.

To fix this you’ll want to call NavigationService.RemoveBackEntry().

To see how this works, make a copy of the previous sample and name the new copy BackStack.  Create a new page, name it Page3.  Put a button on Page 3 to navigate to MainPage, and a second button on MainPage that navigates to Page 3.

Try the following series of steps:

  • Start the application
  • Navigate to Page3
  • Navigate to MainPage
  • Navigate to Page3
  • Navigate to MainPage
  • Navigate to Page2
  • Navigate back to MainPage
  • Press the back button a few times
  • Notice that you back through the dialog box and then you back to page 3

Next, find the OnNavigatedTo method in MainPage and add the RemoveBackEntry call within the if statement as shown here:

protected override void OnNavigatedTo(
    System.Windows.Navigation.NavigationEventArgs e )
{
    string newText = string.Empty;
    if (NavigationContext.QueryString.TryGetValue(
        "DataEntered",
        out newText ))
    {
        DisplayText.Text = newText;
        NavigationService.RemoveBackEntry();
    }
    base.OnNavigatedTo( e );
}

Repeat the steps above. You’ll find that now you no longer step through the dialog box. It has been removed from the backstack.

Complete source code available here.
Related Mango Video available here

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 Essentials, Mango, Mini-Tutorial, WindowsPhone and tagged . Bookmark the permalink.

3 Responses to Removing the BackStack Entry in Windows Phone

Comments are closed.