首先,我想感谢这个解决问题的 Xamarin 答案:How to hide navigation Toolbar icon in xamarin? 这个答案已更新为在 MAUI 中工作,解决方案类似。
最简单的解决方案是通过修改代码隐藏文件中的ToolbarItems 列表来添加或删除项目:
ToolbarItems.Remove(ToolBarItemUpdate);
ToolbarItems.Add(ToolBarItemUpdate);
如果你想要一个IsVisible 属性,你可以通过创建一个自定义控件来添加它。添加此代码:
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); });
}
}
}
然后像这样使用它:
<ContentPage.ToolbarItems>
<mycontrols:BindableToolbarItem
x:Name="ToolBarItemUpdate"
Command="{Binding UpdateCommand}"
Text="Update"
IsVisible="{Binding UpdateIsVisible}"
/>
</ContentPage.ToolbarItems>