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

Share

About Jesse Liberty

Jesse Liberty is a Master Consultant for Falafel Software, and has three decades of experience writing and delivering software projects. He is the author of 2 dozen books and multiple Pluralsight courses, and has been a Technical Evangelist for Telerik and for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS.
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

  1. Pingback: Removing the BackStack Entry in Windows Phone – www.nalli.net

  2. Pingback: Removing the BackStack Entry in Windows Phone | WP7 Developers Links

  3. Patrick Long says:

    Probably worth saying that the very handy RemoveBackEntry method is new in 7.1 (mango)

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>