Programmatically switch between Tabs in a TabbedPage

Viewed 1984

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?

3 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;
}

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.

You could set the current TabbedPage in App.xaml.cs when set the MainPage of App .

in App.xaml.cs

MainPage here is the TabbedPage in your project.

public partial class App : Application
{
    public MainPage CurrentPage { get; }
    public App()
    {
        InitializeComponent();

        MainPage tabbedPage = new MainPage();
        CurrentPage = tabbedPage;

        DependencyService.Register<MockDataStore>();
        MainPage = tabbedPage;
    }
    //...
}

And now you can access it in child page .

protected override bool OnBackButtonPressed()
{

    App currentApp = Application.Current as App;
    var tabbedpage = currentApp.CurrentPage;

    tabbedpage.CurrentPage = tabbedpage.Children[0];

    return true;

}

The above code works fine in my project. If it still doesn't work on your side, you could share a sample so that I can test it .

Related