Checkboxes in WPF are very straight forward controls, very similar to their WinForms predecessors. Adding them is a simple matter of using the <CheckBox> tag. Likely you’ll need to give each a name, so you can reference it in code.
There are also two properties that may be of use to you. First is IsChecked, this is set to true or false and as you might expect sets whether the check is in the box or not. The second is IsEnabled, and determines whether users may use the control. You can combine these in any combination, as you can see in the example below.
<CheckBox Name=“cbxOne“ IsChecked=“False“>Check Box One</CheckBox>
<CheckBox Name=“cbxTwo“ IsChecked=“True“>Check Box Two</CheckBox>
<CheckBox Name=“cbxThree“ IsChecked=“False“ IsEnabled=“False“>Check Box Three</CheckBox>
<CheckBox Name=“cbxFour“ IsChecked=“True“ IsEnabled=“False“>Check Box Four</CheckBox>
<Button Name=“btnShowMe“ Click=“btnShowMe_Click“>Show Me</Button>
This little bit of code produces this attractive dialog:
Note I’ve added a button, the purpose of the button is to show you a dialog that determines whether a box is checked.
void btnShowMe_Click(object sender, RoutedEventArgs e)
StringBuilder sb = new StringBuilder();
sb.AppendLine(“Box One is Checked”);
sb.AppendLine(“Box One is Unchecked”);
sb.AppendLine(“Box Two is Checked”);
sb.AppendLine(“Box Two is Unchecked”);
Here you can see all that’s needed is to check (no pun intended) the IsChecked property. You may wonder why I had to use the bool case in the cbxTwo example. It turns out the IsChecked is actually of type bool? and not bool. A bool? is a bool that can hold a null value in addition to true/false.
In the cbxOne area, the .Net Framework can handle converting the bool? to a bool before it does the equal. In the second example, .Net needs that conversion to be made explicit.
Go ahead and run the app, check the boxes and click the Show Me to see the messages. I didn’t bother to repeat the same code for boxes three and four, since they are disabled, but they’d work the same way.
The WPF CheckBox is something you should check out! (OK, that time the pun was intended! 😉
One thought on “The WPF CheckBox”
It was a really good post. It had really helped.