简体   繁体   中英

How can I skip some stacks to just get the backbutton go to the main page?

I'm having a problem with the backbutton, so I have a function that is only put on action like 5 pages after the MainPage. Than on that fifth page I want to touch the backButton and go to the MainPage(so 5 pages before that one), is there anyway to throw some code to the back button to do this? How can I do this?

EDIT1 "MainPage" is not my root page!!!!

Override the OnBackButtonPressed() method in the code-behind of your page.

If you want to navigate back to the root page, you can call Navigation.PopToRootAsync() :

protected override bool OnBackButtonPressed()
{
    Navigation.PopToRootAsync();
    return true;
}

If you want to navigate back a single page, just Navigation.PopAsync() . If you want to navigate back for example three times, you can call Navigation.PopAsync() three times.

I think Dennis' answer is correct, and it seems you know how many steps you want to go back, so:

protected override bool OnBackButtonPressed()
{
   // Go back 5 steps when the back button is pushed    
   for (var i=0; i<5; i++) {
      Navigation.PopAsync();
   }

   return true;
}

You can get it overriding OnBackButtonPressed() but you have to take care because this override just fire when you press physical button then this solution does not work with iOS just android, for iOS you have to create a custom renderer of the navigation page and replace the default back button for a new one and add the necessary action.

other way to get this approach could be on the OnDisappearing() override of the page

protected override void OnDisappearing()
{
    if (Navigation.NavigationStack.Last() == this)
    {
        Navigation.PopToRootAsync();
    }

    base.OnDisappearing();
}

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