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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With