WPF Checkbox is used to take input from the user in form of pre-defined values. Checkbox provides three state values, which means you can check, uncheck and indeterminate.
Indeterminate means the user is not sure about the selection. But in WPF, checkboxes mostly provide checked and uncheck features, developer rarely used the indeterminate state.
Whenever we install any software, game etc we get an agreement to review, and at the end of the agreement, we get a checkbox to mark as agree or disagree. This is a simple example to recall where the WPF checkbox can be used, but it may vary based on the business logic of your desktop software.
Note: WPF Mouse Event & WPF Keyboard Event can be used on WPF Checkbox.
As usual, you can add a checkbox either by dragging and dropping from ToolBox or by writing the xaml code of the checkbox as follows.
<StackPanel> <CheckBox x:Name="checkBox" Content="CheckBox"/> </StackPanel>
A content attribute will represent the text after the checkbox as you can observe in the following image.
If you want to make a preselected or already checked WPF checkbox you can use the IsChecked property.
<CheckBox x:Name="checkBox" Content="CheckBox" IsChecked="True"/>
If you want to enable the indeterminate state then you have to add the IsThreeState property as follows.
<CheckBox x:Name="checkBox2" Content="YourNameHere" IsThreeState="True"/>
Basically, there are two events of the WPF Checkbox to manipulate the input of the user.
- Checked – It will trigger when the user selects
- Unchecked – It will trigger when the user will unselect
I added both events to the same checkbox as you can see in the code below.
<CheckBox x:Name="checkBox" Content="CheckBox" IsChecked="True" Checked="checkBox_Checked" Unchecked="checkBox_Unchecked"/>
It will generate respective code in C# file
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void checkBox_Checked(object sender, RoutedEventArgs e) { //Write your business logic here, it will trigger when the user checked the checkbox } private void checkBox_Unchecked(object sender, RoutedEventArgs e) { //Write your business logic here, it will trigger when the user unchecked the checkbox } }
Besides the events, if you want to take direct value from the checkbox you can use the following C# Code to get that.
public MainWindow() { InitializeComponent(); bool ValueOfCheckBox = (bool)checkBox.IsChecked; }
Remember one thing, we are explicitly casting “checkBox.IsChecked” by adding (bool) in front.
Because it will return true if the System.Windows.Controls.Primitives.ToggleButton is checked. Return false if the System.Windows.Controls.Primitives.ToggleButton is unchecked and otherwise null. The default value is false.
If you are facing any issues with WPF Checkbox you can contact me.