WPF checkbox IsChecked property does not change according to binding value

checkboxdata-bindingwpf

here is my code:

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>

then I create a ComboBox with item with type "dataType1"

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

and here is dataType1 difinition:

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

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.

Is special handling needed in binding IsChecked property in CheckBox in wpf?

Peter Leung

Best Answer

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;
}

So now, when the property value is changed it will notify the binding that it needs to update by raising the PropertyChanged event.

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.

Related Topic