Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically switch between Tabs in a TabbedPage

I have tabbed page with 4 children(4 tabs), and i want to override back button to allways set first 1 page when you push it. I tried several ways, this seems to make the most sense to me, but it doesn't work - tabbedPage is always null (when i override in all tabs)

protected override bool OnBackButtonPressed()
{
    var tabbedPage = this.Parent as TabbedPage;
    tabbedPage.CurrentPage = tabbedPage.Children[1];
    return base.OnBackButtonPressed();
}

I tried to override this back button in TabbedPage Parent like this:

protected override bool OnBackButtonPressed()
{
    if(CurrentPage == FirstPage)
    {
        return base.OnBackButtonPressed();
    }
    CurrentPage = FirstPage;
    return true;
}

but it always close my app. Any idea why that tabbedPage is null for me?

like image 351
piotruspan Avatar asked Mar 10 '26 04:03

piotruspan


2 Answers

My problem was that my children page is NavigationPage and I should use this.Parent.Parent to cast. So this is how it should be done when u use NavigaionPage as Children of TabbedPage

protected override bool OnBackButtonPressed()
{
    var tabbedPage = this.Parent.Parent as TabbedPage;
    tabbedPage.CurrentPage = tabbedPage.Children[0];
    return true;
}
like image 186
piotruspan Avatar answered Mar 11 '26 16:03

piotruspan


Firstly, when you have TabbedPage, OnBackButtonPressed is being invoked not in the ContentPage, but instead on the TabbedPage itself. So, the correct place to override the method is in the TabbedPage indeed.

Secondly, if you override the method in the TabbedPage itself, it will do the work, like this:

protected override bool OnBackButtonPressed()
{
    var firstPage = Children[0];
    if (CurrentPage == firstPage)
    {
        return base.OnBackButtonPressed();
    }

    CurrentPage = firstPage;
    return true;
}

NB: Be careful what your Children collection is. If you have wrapped your pages in a NavigationPage, the check won't be correct.

like image 24
Mihail Duchev Avatar answered Mar 11 '26 17:03

Mihail Duchev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!