How do I clear the Navigation stack?

后端 未结 5 1234
无人共我
无人共我 2021-02-18 18:03

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 ?

相关标签:
5条回答
  • 2021-02-18 18:08

    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!

    0 讨论(0)
  • 2021-02-18 18:09

    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

    0 讨论(0)
  • 2021-02-18 18:23

    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();
        }
    
    0 讨论(0)
  • 2021-02-18 18:25

    For anyone viewing this in in 2020:

    await Navigation.PopToRootAsync();
    

    or if your using Shell navigation

    await Shell.Current.Navigation.PopToRootAsync();
    
    0 讨论(0)
  • 2021-02-18 18:27

    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();
    
    0 讨论(0)
提交回复
热议问题