How to update the tab bar in .net Maui

1.3k Views Asked by At

My application contains a global tab bar. The tabs in it can change their order, be removed or added and also change visually. Thus I'd like to update the tab bar at runtime. The user should not be moved to a different page, so the navigation stack should not change while updating. I tried to first clear the tab bar items and then add the correct ones back into it. But I encountered multiple problems with this approach, getting exceptions like:

Global routes currently cannot be the only page on the stack, so absolute routing to global routes is not supported. For now, just navigate to: MainPage

I think the problem is that I clear the tabs, as then, for a moment, the shell is empty.

How can I have a dynamic tabbar in .net Maui?

AppShell.xaml:

<Shell
    x:Class="MauiTestApplication.AppShell"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    Shell.FlyoutBehavior="Disabled">

    <TabBar x:Name="MainTabBar"/>

</Shell>

AppShell.xaml.cs:

public void UpdateTabs()
{
   MainTabBar.Items.Clear();
   // Create all tabs
   // Add all tabs to tabbar via: MainTabBar.Items.Add(TAB);
}
1

There are 1 best solutions below

7
Liqun Shen-MSFT On BEST ANSWER

I made a demo to remove and add the tab again .

You could try the following code:

In AppShell.cs

public void UpdateTabs()
{
    //MainTabBar.Items.Clear();

    //  I add these two lines, then it can add the tab in it
    //MainTabBar = new TabBar();
    //this.Items.Add(MainTabBar);

    MainTabBar.Items.Add(new ShellContent()
    {
        Title = "Home",
        ContentTemplate = new DataTemplate(() => new MainPage()),
        Route = "mainpage",
    });

}

Hope it helps.

Create a new TabBar seems to empty the navigation stack. And you could just add and remove the item in it and not let it be empty.

The effect:

enter image description here