简体   繁体   中英

How to remove a current page from stack navigation Xamarin Forms

I'm trying so hard to do something but i wasnt able to solve this problem. I have three pages, One is the MainPage, LoginUpPage and SignUpPage, inside of LoginUpPage has a button who navigates to SignUpPage, what i want to do is when I finish my logic navigates to another page CreatedPage, whitch contains a Label with a Message - Success and then after 2 seconds GoBack to the LoginPage, the problem is if I press the backbutton from device it will return to the last page that has the label with a message and I don't want that. I have a toobar with a BackButton to return to each page that i navigates. So far I have this:

LoginPage to SignUpPage :

Navigation.PushAsync(new SignupPage());

SignUpPage to CreatedPage :

await Navigation.PushModalAsync(new Created());

And inside of CreatedPage in my Contructor, this Method :

    public async void Redirect()
    {
        await Task.Delay(TimeSpan.FromSeconds(2));
        await Navigation.PushAsync(new LoginPage());
    }

I know by this question there's basically three ways to navigate to another page :

Navigation.PushAsync(new OtherPage()); // to show OtherPage and be able to go back

Navigation.PushAsyncModal(new AnotherPage());// to show AnotherPage and not have a Back button

Navigation.PopAsync();// to go back one step on the navigation stack

At the same question has a example how to remove from a page from stack but it doesn't work.

item.Tapped += async (sender, e) => {
await Navigation.PushAsync (new SecondPage ());
Navigation.RemovePage(this);

};

The number of time pages are clicked to and fro, pages gets added to navigation stack. Possibly same page can be in navigation stack many times based on number of clicks.

If there are two or pages on navigation stack.

for (int PageIndex = Navigation.NavigationStack.Count; PageIndex >= 0; PageIndex--)
{  
    Navigation.RemovePage(Navigation.NavigationStack[PageIndex]);
}

This will remove all the pages in the navigation stack excluding the Main Page (or the page at top of Navigation stack)

OR

If user is left with two pages in Navigation Stack and want to make 2nd page in navigation stack as main page (Navigationstack[1]) along with removal of first page(Navigationstack[0]) , It works as below

if (Navigation.NavigationStack.Count == 2)
{
    App.Current.MainPage.Navigation.RemovePage(Navigation.NavigationStack.First());
}

In that case you need to set a Root page :

//Master Detail Page

  public class RootPage : MasterDetailPage
    {
        MenuPage menuPage;

        public RootPage()
        {
            menuPage = new MenuPage(this);
            Master = menuPage;
            Detail = new NavigationPage(new HomePage());
        }
    }

//Set the Root Page
public class App : Application
{
    public App()
    {
       InitializeComponent ();

       if(NewUser || NotLoggedIn)
          {
             MainPage = new LoginPage();
          }
       else
          {
             MainPage = new RootPage();
          }
    }
}

public class LoginPage : ContentPage
    {            
        private void SignupButtonOnClicked(object sender, EventArgs eventArgs)
        {
            Navigation.PushAsync(new SignupPage());
        }
    }


public class SignupPage : ContentPage
    {            
        private void CreatedButtonOnClicked(object sender, EventArgs eventArgs)
        {
            Navigation.PushModalAsync(new CreatedPage());
        }
    }

// Set the Login Page

public class CreatedPage : ContentPage
    {

        private void CreatedButtonOnClicked(object sender, EventArgs eventArgs)
        {
            Navigation.PushModalAsync(new LoginPage());

            //Special Handel for Android Back button
            if (Device.OS == TargetPlatform.Android)
            Application.Current.MainPage = new LoginPage();
        }

    }

In this way back button will not return to previous page as it will reset the Navigation stack to root page ie your LoginPage.

I didn't try this before but you can try this solution:

retrieve your navigation stack as a list:

var existingPages = Navigation.NavigationStack.ToList();

then remove the page you want

then set your navigation stack to the modified list

App.Navigation.RemovePage(App.Navigation.NavigationStack.ElementAt(App.Navigation.NavigationStack.Count - 2));

will remove page after navigated to next page

where App.Navigation is

public static INavigation Navigation { get; set; }

in app class

The easiest way I found to clear a stack and open up a new page on a clear stack

await Navigation.PushAsync(new UserJourneysTabPage()); //Push the page you want to push
            var existingPages = Navigation.NavigationStack.ToList(); 
            //get all the pages in the stack
            foreach (var page in existingPages)
            {
                    //Check they type of the page if its not the 
                    //same type as the newly created one remove it
                    if (page.GetType() == typeof(UserJourneysTabPage))

                    continue;

                Navigation.RemovePage(page);
            }

Note: This doesn't clear a page from the navigation stack if its the same type, but you can always add a property to distinguish the newly created one from the old ones

Iam posting this solution for removing any desired page from the navigation stack using linq.

Here as an example, I am removing all pages except the current active page.

var currentPage = Navigation.NavigationStack[Navigation.NavigationStack.Count - 1];
var pageList = Navigation.NavigationStack.Where(y => y != currentPage).ToList();

foreach(var page in pageList)
    Navigation.RemovePage(page);

The following routine works perfectly for me:

Using System.Linq;

......


try

{

 foreach (var item in Application.Current.MainPage.Navigation.NavigationStack.ToList()

{

       if (item.GetType().Name == "ClientsPage" || item.GetType().Name == "PagoPage")


       {   

           Application.Current.MainPage.Navigation.RemovePage(item);


       }
  }
         
}
catch() {
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM