In this article we will learn how to use CheckBox control in WPF using Visual Basic.NET.
CheckBox control
The CheckBox control is used to display a check box. The CheckBox control gives us an option to select true/false. A checkbox is clicked to select and clicked again to deselect some option. When a checkbox is selected, a check (a tick mark) appears indicating a selection.
Properties - This control has the following properties.
Figure 1.
Content - show the text shown with the CheckBox.
IsChecked: Specifies whether the check box is checked or not.
CheckBox event:
Private Sub CheckBox1_Checked(ByVal sender As System.Object, ByVal e AsSystem.Windows.RoutedEventArgs) Handles CheckBox1.Checked
End Sub
For example:
Drag and drop two CheckBoxes, a TextBox and a Button control on to the form. Set the Text property for the CheckBoxes as Male and Female. The following code will display the text of the CheckBox that is checked in the textbox when the button is clicked. Form looks like this.
Figure 2.
XAML code:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<CheckBox Content="Male" Height="16" HorizontalAlignment="Left" Margin="10,10,0,0"Name="CheckBox1" VerticalAlignment="Top" />
<CheckBox Content="Female" HorizontalAlignment="Left" Margin="10,36,0,0"Name="CheckBox2" Height="16" VerticalAlignment="Top" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="124,12,0,0" Name="TextBox1"VerticalAlignment="Top" Width="120" />
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="156,65,0,0"Name="Button1" VerticalAlignment="Top" Width="75" />
</Grid>
</Window>
Now setting the property Background, Foreground and BorderBrush properties of CheckBox control.
Figure 3.
The form looks like this.
Figure 4.
XAML code
<CheckBox Content="Male" Height="16" HorizontalAlignment="Left" Margin="10,10,0,0"Name="CheckBox1" VerticalAlignment="Top" Background="Blue" BorderBrush="Aqua"Foreground="DarkRed" Width="64" FontSize="14" />
<CheckBox Content="Female" HorizontalAlignment="Left" Margin="10,36,0,0"Name="CheckBox2" Height="16" VerticalAlignment="Top" Background="DarkGreen"BorderBrush="DarkMagenta" Foreground="MediumBlue" Width="64" FontSize="14" />
Now double click on the button control and add the following code.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e AsSystem.Windows.RoutedEventArgs) Handles Button1.Click
If CheckBox1.IsChecked Then
TextBox1.Text = "You are Gender: mail"
ElseIf CheckBox2.IsChecked Then
TextBox1.Text = "Your are Gender:Femail"
End If
End Sub
Now run the application and test it.
Figure 5.
Now tick mark on the CheckBox Female and click on the button.
Figure 6.