首页 文章

WPF复选框IsChecked属性不会根据绑定值更改

提问于
浏览
1

这是我的代码:

xaml方面:我使用数据模板与项“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>

然后我用类型为“dataType1”的项创建一个ComboBox

<ComboBox Name="comboBoxItems" ItemsSource="{Binding Path=DataItems, Mode=TwoWay}">

这里是dataType1 difinition:

class dataType1{public string ItemName{get; set;} public bool IsChecked {get; set;}}

方案是我准备一个dataType1列表并将其绑定到ComboBox,ItemName显示完美无缺,而CheckBox IsChecked值始终未经检查,无论dataType1中的“IsChecked”值如何 .

在Wpf中的CheckBox中绑定IsChecked属性需要特殊处理吗?

彼得梁

1 回答

  • 5

    你在这里遇到的问题是 CheckBox 不知道 dataType1.IsChecked 的值何时发生变化 . 要解决此问题,请将dataType1更改为:

    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 事件来通知绑定它需要更新 .

    此外,有更简单的方法可以避免您必须编写尽可能多的样板代码 . 我用BindableObject from Josh Smith .

相关问题