问题描述
这里是我的代码:
xaml侧:
我使用数据模板绑定项目dataType1
xaml side:I use a data template to bind with item "dataType1"
<DataTemplate DataType="{x:Type dataType1}">
<WrapPanel>
<CheckBox IsChecked="{Binding Path=IsChecked, Mode=TwoWay}" Command="{Binding Path=CheckedCommand} />
<TextBlock Text="{Binding Path=ItemName, Mode=OneWay}" />
</WrapPanel>
</DataTemplate>
$ b b
然后我创建一个ComboBox类型为dataType1的项目
then I create a ComboBox with item with type "dataType1"
<ComboBox Name="comboBoxItems" ItemsSource="{Binding Path=DataItems, Mode=TwoWay}">
这里是dataType1 difinition: / p>
and here is dataType1 difinition:
class dataType1{public string ItemName{get; set;} public bool IsChecked {get; set;}}
这种情况是我准备一个dataType1列表并将其绑定到ComboBox,ItemName显示完美,而CheckBox IsChecked值总是未选中而不管dataType1中的IsChecked的值。
the scenario is I prepare a list of dataType1 and bind it to the ComboBox, ItemName display flawlessly while CheckBox IsChecked value is always unchecked regardless the value of "IsChecked" in dataType1.
在wpf中的CheckBox中绑定IsChecked属性时需要特殊处理吗?
Is special handling needed in binding IsChecked property in CheckBox in wpf?
Peter Leung
Peter Leung
推荐答案
这里的问题是 CheckBox
不知道 dataType1.IsChecked
的值何时更改。要解决这个问题,请将dataType1更改为:
The problem you're having here is that the CheckBox
doesn't know when the value of dataType1.IsChecked
changes. To fix that, change your dataType1 to:
class dataType1 : INotifyPropertyChanged
{
public string ItemName { get; set; }
private bool isChecked;
public bool IsChecked
{
get { return isChecked; }
set
{
if (isChecked != value)
{
isChecked = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("IsChecked"));
}
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
现在,当属性值改变时,它会通知绑定需要通过提高 PropertyChanged
事件进行更新。
So now, when the property value is changed it will notify the binding that it needs to update by raising the PropertyChanged
event.
此外,还有更简单的方法来避免以写入尽可能多的样板代码。我使用 Josh Smith的BindableObject 。
Also, there are easier ways to do this that avoid you having to write as much boiler-plate code. I use BindableObject from Josh Smith.
这篇关于WPF复选框IsChecked属性不会根据绑定值更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!