5

I have a style that I have to create in code-behind. It has a checkbox that looks like this..

<CheckBox 
              HorizontalAlignment="Center"
              VerticalAlignment="Center"
              IsChecked="{Binding Path=DataItem.IsChecked}"
              >
</CheckBox>

How do I replicate this in code-behind?

Aks
  • 5,188
  • 12
  • 60
  • 101
  • Take a look at Carlos' answer here: http://stackoverflow.com/questions/870163/wpf-simple-checkbox-binding-question – abramlimpin Feb 11 '11 at 08:38

2 Answers2

6

Something like this:

CheckBox myCheckBox = new CheckBox();
myCheckBox.HorizontalAlignment = HorizontalAlignment.Center;
myCheckBox.VerticalAlignment = VerticalAlignment.Center;
myCheckBox.SetBinding(ToggleButton.IsCheckedProperty, "DataItem.IsChecked");
Pavlo Glazkov
  • 20,498
  • 3
  • 58
  • 71
  • `myCheckBox.SetBinding(ToggleButton.IsCheckedProperty, "DataItem.IsChecked");` doesn't work. I think its `CheckBox.IsCheckedProperty`. – Aks Feb 11 '11 at 08:48
  • IsCheckedProperty is defined in the ToggleButton class. CheckBox is derived from ToggleButton. What exactly doesn't work? – Pavlo Glazkov Feb 11 '11 at 08:53
  • It doesn't recognize `ToggleButton` as a class. But this works. thanks – Aks Feb 11 '11 at 08:54
0
var myCheckBox = new CheckBox() {DataContext = DataItem };
myCheckBox.SetBinding(ToggleButton.IsCheckedProperty, new Binding(nameof(DataItem.IsChecked));
Reza Karimnia
  • 61
  • 1
  • 9