Search code examples
maui

Hiding ToolbarIcon in MAUI application


In a MAUI application I have a toolbar item like this:

<ContentPage.ToolbarItems>
   <ToolbarItem 
       x:Name="ToolBarItemUpdate"
       Command="{Binding UpdateCommand}"
       Text="Update" />
<ContentPage.ToolbarItems>

How can I hide this item? There is no IsVisible property.


Solution

  • The most simple solution is to add or remove the item by modifying the ToolbarItems list in the code behind file:

    ToolbarItems.Remove(ToolBarItemUpdate);
    ToolbarItems.Add(ToolBarItemUpdate);
    

    But if you want to use MVVM, it is not that easy. My solution binds the property to a hidden switch, that then makes a callback to the code behind controls the visibility. Would love to have a better solution :-) First, I have a toolbar item like this:

    <ContentPage.ToolbarItems>
        <ToolbarItem 
                x:Name="ToolbarItemAlbumMode"
                Text="Show album"
                Order="Secondary"
                Priority="0" />
    </ContentPage.ToolbarItems>
    

    And then my hidden switch:

    <VerticalStackLayout IsVisible="False">
        <Switch 
            x:Name="ToolbarHelperAlbum"
            IsToggled="{Binding HasAlbum, Mode=OneWay}"
            Toggled="ToolbarHelper_ToggleChanged"
            />
    </VerticalStackLayout>
    

    And then this in the code behind:

    protected override void OnAppearing()
    {
        base.OnAppearing();
        
        RefreshToolbarItems();
    }
    
    private void RefreshToolbarItems()
    {
        SetToolbarItemVisibility(ToolbarItemAlbumMode, ViewModel.HasAlbum);
    }
    
    private void ToolbarHelper_ToggleChanged(object sender, ToggledEventArgs e)
    {
        RefreshToolbarItems();
    }
    
    public void SetToolbarItemVisibility(ToolbarItem toolbarItem, Microsoft.Maui.Controls.Switch switchControl)
    {
        SetToolbarItemVisibility(toolbarItem, switchControl.IsToggled);
    }
    
    public void SetToolbarItemVisibility(ToolbarItem toolbarItem, bool value)
    {
        if (value && !ToolbarItems.Contains(toolbarItem))
        {
            ToolbarItems.Add(toolbarItem);
        }
        else if (!value)
        {
            ToolbarItems.Remove(toolbarItem);
        }
    }