Search code examples
c#.nettabsmaui

How to iterate on TabBar children and how to access TabBar object from Shell in a MAUI application?


I have on MainPage of Application a Shell with TabBar with many Tab(s).

I would like to know if there is any possibility to find out in C# code tab titles from TabBar from Shell in a .NET MAUI application

I require to memorize in a model if the tabs are visible or not and would not like the approach to entry them by hand. An iteration on TabBar children would avoid this.

Application is .Net 6 MAUI version.

I tried finding out ways to access TabBar object from Shell but could not find any way in Shell object API.


Solution

  • The TabBar is part of the Shell so to get to the current shell object you need to use the Current property that holds this instance of the Shell. With this you find all the Items in the shell, which is a ShellItemCollection, ie TabBar.

    var shell = Shell.Current;  // Active Shell
    var tabBar = shell.Items.Where(i => i.Title == "TabBarTitle").FirstOrDefault(); // The TabBar - give the TabBar a unique title in the XAML file
    var allShellItems = tabBar.Items; // All our Tabs
    

    To get all the visable tabs is a bit tricky. But if you look inside the class ShellItem you find GetItems

    ReadOnlyCollection<ShellSection> IShellItemController.GetItems() => ((ShellSectionCollection)Items).VisibleItemsReadOnly;
    

    This is part of IShellItemController that ShellItem, ie TabBar, inherent so we get to use it like this.

    var visableItems = (tabBar as IShellItemController).GetItems();
    

    To put it all together and clean it up a bit we can put this in a List that gives us all information about our tabs

    private List<TabBarItemElement> GetCurrentTabBarList()
    {
        var tabBarItems = new List<TabBarItemElement>();
        var tabBar = Shell.Current.Items.Where(i => i.Title == "TabBarTitle").FirstOrDefault();
        var visableItems = (tabBar as IShellItemController).GetItems();
        foreach (ShellSection item in tabBar.Items)
        {
            tabBarItems.Add(new TabBarItemElement
            {
                Title = item.Title,
                Icon = item.Icon,
                IsVisable = visableItems.Contains(item)
            });
        }
    
        return tabBarItems;
    }
    
    private class TabBarItemElement
    {
        public string Title { get; set; }
        public ImageSource Icon { get; set; }
    
        public bool IsVisable { get; set; }
    }