1

我有ComboBox一个 UWP 项目。我将 绑定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>

我该如何解决这个问题?

编辑 1:绑定代码

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

1 回答 1

1

只需ItemsSource="{Binding Path=MyItemsCollection, UpdateSourceTrigger=PropertyChanged}"在 XAML 中删除此行 ( ) 并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}">
  ....
于 2015-08-02T17:09:33.257 回答