Clearing backstack in NavigationService
Asked Answered
H

2

9

I am navigating through different pages within my application. After I login, I come to home page from where the navigation starts. During navigation, when I come to homepage, I want to go to the login page by pressing BackKey but I can only navigate to previously navigated page. I could have overriden the BackKeyPress event to navigate to the Login Page but in LoginPage I should again override the Backkeypress otherwise there appears to be cycle between loginpage and homepage on backkey press. Is there anyway to clear the navigation history?

Haha answered 23/11, 2011 at 11:37 Comment(0)
G
22

You can use NavigationService.RemoveBackEntry: http://msdn.microsoft.com/en-us/library/system.windows.navigation.navigationservice.removebackentry%28v=VS.92%29.aspx

For instance, to remove all entries from the stack:

while (this.NavigationService.BackStack.Any())
{
   this.NavigationService.RemoveBackEntry();
}


Also, if you want to remove only the previous page after checking its URI:
var previousPage = this.NavigationService.BackStack.FirstOrDefault();

if (previousPage != null && previousPage.Source.ToString().StartsWith("/MainPage.xaml"))
{
    this.NavigationService.RemoveBackEntry();
}
Gilda answered 23/11, 2011 at 12:5 Comment(2)
RemoveBackEntry sometimes throws NullReferenceException. Some logic inside navigation system is broken so on FAS it sometiems adds phantom journalentries with PageInstance == null.Zia
If I wanted to remove only a single page, since my Navigation is A then B, and I want to remove A, I would just call this.NavigationService.RemoveBackEntry(); in the OnNavigatedTo event? I would use a querystring from A to B just to be sure that the navigation to B was from A.Liederman
H
0

While I know the original question was for 7, in Windows Phone 8.1 the NavigationService no longer exists.

Here is the Windows Phone 8.1 code

 var previousPage = this.Frame.BackStack.FirstOrDefault();

 if (previousPage != null && previousPage.SourcePageType == typeof(MainPage))
 {
     this.Frame.BackStack.RemoveAt(this.Frame.BackStackDepth - 1);
 }
Heir answered 25/9, 2014 at 14:55 Comment(1)
It does. I'm Using it in my Windows Phone 8.1 Silverlight App.Canarese

© 2022 - 2024 — McMap. All rights reserved.