1
votes

I have 3 pages in my application- MainPage, Page1 and Page2.

Page2 contains a button , when the button is clicked the following code gets executed-

Navigation.PushAsync(new Page1());

Page 1 gets loaded.

Now when I press the back button on Page1, I want it to load the MainPage, but instead Page2 gets loaded.

I have tried overriding the back button-

        protected override bool OnBackButtonPressed()
        {
            Navigation.PushAsync(new MainPage());
            return true;
        }

And also using

 Navigation.PopAsync();

But neither of them worked.

2
Page2 --> Page1, so back will naturally go to Page2, which is the previous page.Jason
It doesn't load Page2 when you press the back button on Page1, because Page2 wasn't unloaded when you pushed Page1. Page1 appeared on top and when you tap the back button it's removed, Page2 having been there all along.Robot Head
On your button in Page2, try loading Page1 then poping Page2, so that as soon as Page1 loads, Page2 is unloaded. Then Page2 won't be there when you press the back button on Page1. Assuming MainPage has always been there, MainPage will then be revealed.Robot Head

2 Answers

1
votes

If MainPage is the root page, try using the Navigation.PopToRoot() function.

0
votes

The OnBackButtonPressed event will get fired only on Android when the user press the hardware back button.

protected override bool OnBackButtonPressed()
{
    Device.BeginInvokeOnMainThread(async () =>
    {
        base.OnBackButtonPressed();
        await Navigation.PopAsync(true); //Asynchronously removes the top Page from the navigation stack.
    });
    return true;
}