This article demonstrates how to create and use a CheckBox control at design-time using XAML.
Similar to any XAML conntrol, the CheckBox has common properties.
The following code snippet creates a CheckBox control and sets its name, content, foreground and font related properties.
- <CheckBox Name="McCheckBox" Foreground="Orange"
- Canvas.Left="20" Canvas.Top="10" Content="Check Me"
- FontFamily="Georgia" FontSize="20" FontWeight="Bold" >
- </CheckBox>
The IsChecked property represents the state of the CheckBox control. The IsThreeState property represents whether the CheckBox has two or three states. The three states are checked, unchecked and indeterminate. The following code example sets the IsChecked and IsThreeState properties of the CheckBox.
- <CheckBox Name="McCheckBox"
- Canvas.Left="10" Canvas.Top="10"
- Content="Check Me"
- IsChecked="True" IsThreeState="True" >
- </CheckBox>
Adding a CheckBox Click Event Handler
The Checked and Unchecked attributes of the CheckBox element adds the checked and unchecked event handler. These events are fired when a CheckBox state is changed to checked and unchecked respectively.
- <CheckBox Name="McCheckBox"
- Canvas.Left="10" Canvas.Top="10"
- Content="Check Me"
- IsChecked="True" IsThreeState="True"
- Checked="McCheckBox_Checked" Unchecked="McCheckBox_Unchecked">
- </CheckBox>
The code for the click event handler looks like the following.
- private void McCheckBox_Checked(object sender, RoutedEventArgs e)
- {
- }
- private void McCheckBox_Unchecked(object sender, RoutedEventArgs e)
- {
- }
The code listed below sets the content of a CheckBox on both checked and unchecked events. When you check or uncheck the CheckBox, you will see the content of the CheckBox changing.
- private void McCheckBox_Checked(object sender, RoutedEventArgs e)
- {
- McCheckBox.Content= "Checked";
- }
- private void McCheckBox_Unchecked(object sender, RoutedEventArgs e)
- {
- McCheckBox.Content= "Unchecked";
- }
Here is a more detailed tutorial on WPF CheckBox:
WPF CheckBox Control