In my app I\'m pushing pages using a NavigationPage
and at some stage I want to go back to a previous page in the stack. This is my structure:
NavigationPag
I came with a solution which can go back to an specific page as long as you have a reference to it:
protected async Task PopToPage(Page destination)
{
if (destination == null) return;
//First, we get the navigation stack as a list
var pages = Navigation.NavigationStack.ToList();
//Then we invert it because it's from first to last and we need in the inverse order
pages.Reverse();
//Then we discard the current page
pages.RemoveAt(0);
foreach (var page in pages)
{
if (page == destination) break; //We found it.
toRemove.Add(page);
}
foreach (var rvPage in toRemove)
{
navigation.RemovePage(rvPage);
}
await Navigation.PopAsync();
}
If you have a count that you would like to pop, this works really well for me.
for(i=1; i < size; i++) { if (Device.OS == TargetPlatform.Android) { Navigation.RemovePage(Navigation.NavigationStack[Navigation.NavigationStack.Count - 1]); } else { Navigation.RemovePage(Navigation.NavigationStack[Navigation.NavigationStack.Count - 2]); } } await Navigation.PopAsync();
This worked exceptionally well for me:
I set up a counter and threw a DisplayAlert to find out how many pages I needed to remove
var x = Navigation.NavigationStack.Count();
DisplayAlert("Page Count", x.ToString(), "OK");
And then used that to remove the number I needed to fall back.
Navigation.RemovePage(Navigation.NavigationStack[Navigation.NavigationStack.Count - 2]);
await Navigation.PopAsync();
If you have a count that you would like to pop, this works really well.
for (var counter = 1; counter < BackCount; counter++)
{
Navigation.RemovePage(Navigation.NavigationStack[Navigation.NavigationStack.Count - 2]);
}
await Navigation.PopAsync();
I was trying to do the same thing - what I've wound up doing is a bit of a hack, but does work and keep the back button of page 2 going to page 1.
Basically,
var page3 = _navi.NavigationStack.FirstOrDefault(p => p is Page3Type);
if(page3 != null)
{
_navi.RemovePage(page3);
}
await navi.PopAsync();
What this does is first, if present, remove page3. Now that that's gone, it pops, and you're back at page 2.