0

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.

PEK
  • 3,688
  • 2
  • 31
  • 49

1 Answers1

2

First, I want to give credit to this Xamarin answer that solved the problem: How to hide navigation Toolbar icon in xamarin? This answer is updated to work in MAUI, the solution is similar.

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);

If you want an IsVisible property, you could add that by creating a custom control. Add this code:

internal sealed class BindableToolbarItem : ToolbarItem
{
    private IList<ToolbarItem>? ToolbarItems { get; set; }

    public static readonly BindableProperty IsVisibleProperty =
        BindableProperty.Create(nameof(IsVisible), typeof(bool), typeof(BindableToolbarItem), true, BindingMode.OneWay, propertyChanged: OnIsVisibleChanged);

    public bool IsVisible
    {
        get => (bool)GetValue(IsVisibleProperty);
        set => SetValue(IsVisibleProperty, value);
    }

    private static void OnIsVisibleChanged(BindableObject bindable, object oldvalue, object newvalue)
    {
        var item = (BindableToolbarItem)bindable;

        item.RefreshVisibility();
    }

    protected override void OnParentChanged()
    {
        base.OnParentChanged();

        IList<ToolbarItem>? parentToolbarItems = (Parent as ContentPage)?.ToolbarItems;

        if (parentToolbarItems is not null)
        {
            ToolbarItems = parentToolbarItems;
        }

        RefreshVisibility();
    }

    private void RefreshVisibility()
    {
        if (ToolbarItems is null)
        {
            return;
        }

        bool value = IsVisible;

        if (value && !ToolbarItems.Contains(this))
        {
            Application.Current!.Dispatcher.Dispatch(() => { ToolbarItems.Add(this); });
        }
        else if (!value && ToolbarItems.Contains(this))
        {
            Application.Current!.Dispatcher.Dispatch(() => { ToolbarItems.Remove(this); });
        }
    }
}

And then use it like this:

<ContentPage.ToolbarItems>
   <mycontrols:BindableToolbarItem 
      x:Name="ToolBarItemUpdate"
      Command="{Binding UpdateCommand}"
      Text="Update"
      IsVisible="{Binding UpdateIsVisible}"
      />
</ContentPage.ToolbarItems>
PEK
  • 3,688
  • 2
  • 31
  • 49