我在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>
我该如何解决这个问题?
编辑1 :绑定代码
<ComboBox ItemsSource="{Binding Path=MyItemsCollection, UpdateSourceTrigger=PropertyChanged}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=ItemName}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
答案 0 :(得分:1)
只需在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}">
....