Anand
Anand

Reputation: 1959

Remove multiple pages from stack- xamarin.forms

I have a xamarin.forms app which has several screens. The navigation of my pages is like this.

1 --> 2 --> 3 --> 4 --> 5 --> 6

The 6th page is popup created using Rg.plugin.popup.User can navigate to and forth as many times in this hierarchy. But when they reach 6th page there is a button. In the button click it should navigate user to 2nd page. How can I remove all the pages ie; 3,4,5 from stack and go to 2nd page.

What I tried

on button click :

for (var i = 1; i < countPagesToRemove; i++)
{
    Navigation.RemovePage(Navigation.NavigationStack[Navigation.NavigationStack.Count - 2]);
}
await Navigation.PopAsync();

This link ask same question but it doesn't work for me.

Then I tried like this

await PopupNavigation.Instance.PopAsync();
Application.Current.MainPage = new NavigationPage(new NCDashboard());

It will navigate to 2nd page but will not show back button to first page due to nothing in the stack. So how can I solve this problem? Any help is appreciated.

Upvotes: 0

Views: 2812

Answers (2)

Wendy Zang - MSFT
Wendy Zang - MSFT

Reputation: 10958

Updated:

The code on Page6 works well.

    protected override void OnAppearing()
    {
        base.OnAppearing();
        for (var i = 1; i <= 3; i++)
        {
            Navigation.RemovePage(Navigation.NavigationStack[Navigation.NavigationStack.Count - 1]);
        }
    }
    private async void Button_Clicked(object sender, EventArgs e)
    {                    
        await PopupNavigation.PopAsync();
    }

enter image description here

Upvotes: 1

Reed
Reed

Reputation: 1261

You're calling RemovePage from the 6th page, which is Rg.Popups PopupPage. As we've discussed in the comments, Rg.Popups PopupPage doesn't go onto the same stack as regular Xamarin.Forms pages. You need to get reference to the stack where the pages from 1st to 5th sits and execute RemovePage on it. Try out the following workaround:

    var mainPage = (Application.Current.MainPage as NavigationPage);
    for (var i = 1; i < countPagesToRemove; i++)
    {

     mainPage.Navigation.RemovePage(mainPage.Navigation.NavigationStack[mainPage.Navigation.NavigationStack.Count - 2]);
    }
    await Navigation.PopAsync();

Upvotes: 1

Related Questions