I have problem for Navigation in my app. I use xamarin.forms how can clean my navigation stack. No use Pop and push. Can I see my full navigation stack ?
You can try this...
public void ResetNavigationStack()
{
if (_navigation != null && _navigation.NavigationStack.Count() > 0)
{
var existingPages = _navigation.NavigationStack.ToList();
foreach (var page in existingPages)
{
_navigation.RemovePage(page);
}
}
}
and BOOOM!!! that nav stack is cleared brotha!
Or if you wanna reset the modal stack
public async Task<Page> PopAllModals()
{
Page root = null;
if (_navigation.ModalStack.Count() == 0)
return null;
for (var i = 0; i <= _navigation.ModalStack.Count(); i++)
{
root = await _navigation.PopModalAsync(false);
}
return root;
}
And BOOOM! those modals are gone!
In the latest version of Xamarin.Forms you can see your navigation stack using
Navigation.NavigationStack
therefore you could use a
var existingPages = Navigation.NavigationStack.ToList();
foreach(var page in existingPages)
{
Navigation.RemovePage(page);
}
This code would have to go into your code behind of a Navigation Page or something that implements INavigation.
More information Xamarin.Forms.INavigation Members
This is a function I made to empty the stack and navigate to a specified page. (The use case was the app was de-activated during use and I need to kick the user out)
public async Task PopAllTo(ViewModel vm)
{
if (vm == null) return;
Page page = PreparePage(vm); //replace 'page' with the page you want to reset to
if (page == null) return;
_navigation.InsertPageBefore(page, _navigation.NavigationStack.First());
await _navigation.PopToRootAsync();
}
For anyone viewing this in in 2020:
await Navigation.PopToRootAsync();
or if your using Shell navigation
await Shell.Current.Navigation.PopToRootAsync();
You can access the navigation stack of your application by calling: Navigation.NavigationStack.
In my opinion the best approach is to parse the navigation stack to a list and clear it:
Navigation.NavigationStack.ToList().Clear();