Search code examples
iconsmauititlebar

Dynamically add Icons to titlebar Maui


Im creating an App where I want have multiple icons in my titlebar (they should be clickable). One Icon should be on the Left of the title text like so (this icon is static and will not change):

enter image description here

The other Icons should be on the right (these icons should be dynamic, as they will be used to alert the user if anything important happens):

enter image description here

I'm using a simple shell, so no Navigationpage, thus I don't think <NavigationPage.Titleview> can be used in this case. Is there any way to achieve something like this in Maui?


Solution

  • You can use the shell title view as stated in this answer, it is pointing to Xamarin documentation but it is also valid for MAUI.

    In your case you will have something like this inside your AppShell.xaml :

    <Shell.TitleView>
        <Grid ColumnDefinitions="auto,*,auto">
            <Label Text="Title" BackgroundColor="Red"></Label>
            <HorizontalStackLayout Grid.Column="2">
                <Label Text="Icon" BackgroundColor="Red"></Label>
            </HorizontalStackLayout>
        </Grid>
    </Shell.TitleView>
    

    Which look like this (very trendy design) :

    Title view result

    How to update the icons can be done by data binding or creating directly the object from C# :

            <HorizontalStackLayout Grid.Column="2" x:Name="IconsContainer">
                <Label Text="Icon" BackgroundColor="Red" IsVisible="{Binding Icon1Visible}"></Label>
            </HorizontalStackLayout>
    

    And in the C# :

    public partial class AppShell : Shell
    {
        public bool Icon1Visible { get; set; } = false;
    
        public AppShell()
        {
            InitializeComponent();
            // An object containing the binding data
            BindingContext = this;
    
            // Directly create a new icon
            AddIcon();
    
            // Show an icon through binding
            ShowIcon();
        }
    
        public void ShowIcon()
        {
            Icon1Visible = true;
        }
    
        public void AddIcon()
        {
            var icon = new Label();
            icon.Text = "And another one";
            IconsContainer.Children.Add(icon);
        }
    }
    

    To get whenever you want to update the icons I would go with dependency injection and either pass directly a view model to bind the icons on or using events.