How to PopAsync more than 1 page in Xamarin Forms Navigation?

前端 未结 5 980
一生所求
一生所求 2021-02-07 04:27

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

相关标签:
5条回答
  • 2021-02-07 04:31

    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();
    }
    
    0 讨论(0)
  • 2021-02-07 04:46

    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();
    
    0 讨论(0)
  • 2021-02-07 04:46

    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();
    
    0 讨论(0)
  • 2021-02-07 04:49

    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();
    
    0 讨论(0)
  • 2021-02-07 04:54

    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.

    0 讨论(0)
提交回复
热议问题