Introduction
CheckBox represents a control that a user can select (check)
or clear (uncheck) form a list of options that a user can select, such as
a list of settings to apply to an application. Both CheckBox and RadioButton controls
allow the user to select from a list of options. CheckBox controls allow the
user to select a combination of options. In contrast, RadioButton controls
allow the user to select from mutually exclusive options.
In the following demo, we are listing some skills from which user can select and the selected will be shown in a TextBlock shown below and unchecking the same will remove it also.
Step 1
Open a blank app and add some CheckBox and a Textblock control either from the toolbox or by copying the following XAML code into your grid.
- <StackPanel>
- <TextBlock Text="Check Box" FontSize="20"></TextBlock>
- <StackPanel Margin="10,10,0,0" Orientation="Horizontal">
- <TextBlock Text="Select your skills"></TextBlock>
- <StackPanel>
- <CheckBox Margin="20,0,0,0" Content="C#" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked"></CheckBox>
- <CheckBox Margin="20,0,0,0" Content="XAML" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked"></CheckBox>
- <CheckBox Margin="20,0,0,0" Content="HTML" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked"></CheckBox>
- <CheckBox Margin="20,0,0,0" Content="JAVA" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked"></CheckBox>
- <CheckBox Margin="20,0,0,0" Content="SQL" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked"></CheckBox>
- </StackPanel>
- </StackPanel>
- <TextBlock Name="selectedSkills" Margin="20,10,0,0" Foreground="Green"></TextBlock>
- </StackPanel>
All checkboxes and navigating to the same event handler while getting checked or unchecked.
Step 2
Add the following code to your cs page to handle the event handlers while being getting checked or unchecked.
- List<string> selected = new List<string>();
-
- private void CheckBox_Checked(object sender, RoutedEventArgs e)
- {
- CheckBox cb = sender as CheckBox;
- selected.Add(cb.Content.ToString());
- selectedSkills.Text = "Your skills are " + String.Join(", ", selected);
-
- }
-
- private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
- {
- CheckBox cb = sender as CheckBox;
- selected.Remove(cb.Content.ToString());
- selectedSkills.Text = "Your skills are " + String.Join(", ", selected);
- }
Here we have created a list of strings to which the content value of each CheckBox get added or removed while getting checked and unchecked respectively.
Step 3
Run your application and check yourself.
Summary
In this article, we learned about CheckBox Control For Windows10.