I'm trying to create an App where Tabs can be dynamically added and removed during runtime. I have a Tabbar in my AppShell.xaml, as seen in the following code sample:
<Shell
x:Class="foo.AppShell"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:foo"
xmlns:views="clr-namespace:foo.Views"
Shell.FlyoutBehavior="Disabled"
Shell.BackgroundColor="{DynamicResource ShellBackGroundColor}">
<TabBar x:Name="MainTabBar">
<ShellContent Title="Home"
Icon="alert_icon_2_neg.png"
ContentTemplate="{DataTemplate views:StartPage}">
</ShellContent>
</TabBar>
</Shell>
The code I use to update the Tabs is the following:
public void UpdateTabs(ObservableCollection<UserAction> list)
{
MainTabBar.Items.Clear();
foreach (UserAction action in list)
{
MainTabBar.Items.Add(new ShellContent()
{
Title = action.Title,
Icon = action.ImageSource,
ContentTemplate = new DataTemplate(() => action.ActionPage),
Route = action.Title
});
}
}
After this method is executed the MainTabBar.Items list has the correct shellcontents in it, however the Tabs are not displayed in the UI. How could I achieve this?
Also, I am aware of the similarities between this and a question asked by User Bagroy (How dynamically add tabs in code behind to Maui Shell TabBar?) but the solutions given in response to his question do not work for me.
Based on the code, seems that using MainTabBar.Items.Clear();
then Tabbar not display.
So the workaround here is to add this code after clear the Items,
MainTabBar.Items.Clear();
//add the following two lines
MainTabBar = new TabBar();
this.Items.Add(MainTabBar);
Hope it works for you.