9

I have 3 pages in my app. Page # 2 navigates back to page #1 and forward to Page # 3. How can I make it so navigating back from page #3 would skip page # 2 and go directly to #1?

Sergey Aldoukhov
  • 22,316
  • 18
  • 72
  • 99

7 Answers7

6

What I ended up with, is combining pages #2 and #3 in one page. When I need page#2, I use navigation parameter to start the page with #2 content visible, when I'm done with #3, I simply hide #2 content.

EDIT: In Mango, there is a NavigationService.RemoveBackEntry() function that does exactly what is needed.

Sergey Aldoukhov
  • 22,316
  • 18
  • 72
  • 99
4

There's no way to go directly from page#3 to page#1 without going through page#2.

You could however handle OnNavigatedTo in Page#2 and if coming from Page#3 then issue another call to NavigationService.GoBack().
Something like:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
  if (comingFromPage3)
  {
    NavigationService.GoBack();
  }

  base.OnNavigatedTo(e);
}

There are various ways you could track if coming from page#3. I'd be tempted to go with a global variable to indicate this (set in page#3 and checked in page#2).
If you decide to use simple tracking of how many times the page has been navigated to (i.e. the second time the page is navigated to it must be in return from #3) be careful about what happens when tombstoned when either page#2 or page#3 is displayed.

Matt Lacey
  • 65,560
  • 11
  • 91
  • 143
2

If you are using the hardware back button, then no there is no direct way to do this.

You could always use the navigate method to go directly to page one.

  NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));

That will get you to the first page but it will also add page 3 to the back stack.

In WPF you can always use the RemoveBackEntry() method to clear items from the back stack but unfortunately it's not available in Silverlight for the phone.

Walt Ritscher
  • 6,977
  • 1
  • 28
  • 35
1

I recommend overiding the back button key press to direct the user where you want them to go:

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) { NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative)); }

1

You can now remove pages from the back stack directly. See this thread for more information:

Clearing backstack in NavigationService

Community
  • 1
  • 1
0

You should create "Loaded" event for your page

    private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
    {
        try { while (NavigationService.RemoveBackEntry() != null) ; }
        catch (System.NullReferenceException ex) { }
    }
Sorokin Andrey
  • 419
  • 5
  • 12
0

Instead of Page #2 navigating specifically to Page #1 consider using this code:-

NavigationService.GoBack();
AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306