通过绑定数据bool来禁用comboxboxitem

本文关键字:comboxboxitem bool 绑定 数据 | 更新日期: 2023-09-27 18:05:53

我在UWP项目中有一个ComboBox。我将DataSource绑定到MyItem类的集合。我的类是这样的:

public class MyItem : INotifyPropertyChanged
{
    #region INPC
    public event PropertyChangedEventHandler PropertyChanged;
    protected void Notify(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #endregion
    private string _ItemName;
    public string ItemName
    {
        get { return _ItemName; }
        set
        {
            if (value != _ItemName)
            {
                _ItemName = value;
                Notify("ItemName");
            }
        }
    }
    private bool _ItemEnabled;
    public bool ItemEnabled
    {
        get { return _ItemEnabled; }
        set
        {
            if (value != _ItemEnabled)
            {
                _ItemEnabled = value;
                Notify("ItemEnabled");
            }
        }
    }}

现在我想要启用或禁用ComboBoxItem取决于我的ItemEnabled属性。我研究并尝试通过Style标签添加绑定,但该绑定在UWP中不起作用。

<ComboBox.ItemContainerStyle>
      <Style TargetType="ComboBoxItem">
         <Setter Property="IsEnabled" Value="{Binding ItemEnabled}" />
      </Style>
</ComboBox.ItemContainerStyle>

我该如何解决这个问题?

EDIT 1: Binding code

<ComboBox ItemsSource="{Binding Path=MyItemsCollection, UpdateSourceTrigger=PropertyChanged}">           
  <ComboBox.ItemTemplate> 
    <DataTemplate>      
      <TextBlock Text="{Binding Path=ItemName}" />  
    </DataTemplate>
   </ComboBox.ItemTemplate> 
</ComboBox>

通过绑定数据bool来禁用comboxboxitem

在XAML中删除这一行(ItemsSource="{Binding Path=MyItemsCollection, UpdateSourceTrigger=PropertyChanged}"),并在InitializeComponent();后面的代码中添加这一行:

<ComboBox Name="cmb1">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=ItemName}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
    <ComboBox.ItemContainerStyle>
        <Style TargetType="ComboBoxItem">
           <Setter Property="IsEnabled" Value="{Binding ItemEnabled}" />
        </Style>
    </ComboBox.ItemContainerStyle>
</ComboBox>

xaml.cs:

public Window1()
{
    InitializeComponent();
    cmb1.ItemsSource = MyItemsCollection;
}

编辑:另一种方法是这样的:

public Window1()
{
   InitializeComponent();
   this.DataContext = MyItemsCollection;
}

在xaml:

<ComboBox Name="cmb1" ItemsSource="{Binding}">
  ....