Search code examples
androidxamarin.formstabbedpage

Xamarin.Forms Adding Children Pages to TabbedPage


My Main Page in my App is a TabbedPage

I have three Tabs:

Payment, Config, Maintain

One of the tabs is controlled by a setting to show it or not. When that is changed to false I remove the tab by doing the following:

tabPage.Children.Remove(ConfigTab);

This removal works fine. If I turn the tab back on I can Add the tab by using this code:

tabPage.Children.Add(ConfigTab);

But its added at the end of the list and the Navigation header is missing:

enter image description here

I looked at using the Insert method where I can sepcify an index

tabPage.Children.Insert(1,ConfigTab);

but this crashed the app with the following message:

Unhandled Exception: Java.Lang.IndexOutOfBoundsException: Invalid index 2, size is 2

If I inspect the children at that point it has added the page at the correct index

Any suggestions on how I can dynamically insert a new page to a TabbedPage? And retain the navigation?

UPDATE:

I have now managed to get it working by doing the following :

var paymentPage = tabPage.Children.FirstOrDefault(p=> p.ClassId == "PaymentNavPage");
var configPage = GetConfigPage();
var maintenancePage = tabPage.Children.FirstOrDefault(p => p.ClassId == "MaintaintNavPage");

// Clear old Tabgs
tabPage.Children.Clear();

// Put pages back
tabPage.Children.Add(paymentPage);
tabPage.Children.Add(configPage);
tabPage.Children.Add(maintenancePage);              

I'm still interested if there is a better way to use the Insert method and then to reset the Navigation Stack.


Solution

  • I'm experiencing the same thing with Insert to the Children. Your solution seems to be the only option to hide and show a page. I would suggest assigning the pages to variables so you don't have to loop through the Children every time you are hiding/showing ConfigPage. Based on the names I'm assuming that the pages are different from each other.

    In the case of similar pages ItemsSource can be used with the help of DataTemplate. When binding the ItemsSource to ObservableCollection hiding and showing pages requires just to modify that collection. More info about that can be found here:

    https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/navigation/tabbed-page/#Populating_a_TabbedPage_with_a_Template