【问题标题】:Hiding ToolbarIcon in MAUI application在 MAUI 应用程序中隐藏 ToolbarIcon
【发布时间】:2022-11-14 04:28:50
【问题描述】:

在 MAUI 应用程序中,我有一个像这样的工具栏项目:

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

我怎样才能隐藏这个项目?没有IsVisible 属性。

【问题讨论】:

    标签: maui


    【解决方案1】:

    首先,我想感谢这个解决问题的 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>
    

    【讨论】:

      猜你喜欢
      • 2011-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-19
      • 2013-03-07
      • 2019-01-05
      • 2011-10-29
      相关资源
      最近更新 更多