views:

2119

answers:

2

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

+3  A: 

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.

Wilka
Sorry for missing the detail that i have already implement INotifyPropertyChanged in dataType1 suggested by Wilka. Actually i am using MVVM model and I got a List<dataType1> in ViewModel. List<dataType1> also implemented propertyChanged method. but checkbox still unable to show value of IsChecked.
Peter Leung
A: 

I am having the same problem. The CheckBox shows up as disable. If I remove the Command on the CheckBox, the CheckBox is enabled but obviously not wired up to anything. Sorry I don't have an answer but at least you are not alone.

Ciband