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?

1

2 Answers 2

6

Something like this:

CheckBox myCheckBox = new CheckBox();
myCheckBox.HorizontalAlignment = HorizontalAlignment.Center;
myCheckBox.VerticalAlignment = VerticalAlignment.Center;
myCheckBox.SetBinding(ToggleButton.IsCheckedProperty, "DataItem.IsChecked");
Sign up to request clarification or add additional context in comments.

3 Comments

myCheckBox.SetBinding(ToggleButton.IsCheckedProperty, "DataItem.IsChecked"); doesn't work. I think its CheckBox.IsCheckedProperty.
IsCheckedProperty is defined in the ToggleButton class. CheckBox is derived from ToggleButton. What exactly doesn't work?
It doesn't recognize ToggleButton as a class. But this works. thanks
1
var myCheckBox = new CheckBox() {DataContext = DataItem };
myCheckBox.SetBinding(ToggleButton.IsCheckedProperty, new Binding(nameof(DataItem.IsChecked));

1 Comment

Please add some explanation to your answer such that others can learn from it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.