WPF: A simple checkbox

This entry is part 13 of 54 in the series Learn WPF

This simple example shows how to create Checkbox controls and add event handlers.

When a user clicks the Checkbox the text of the control changes. The Checkbox is created using XAML.

MainWindow.xaml
<Window x:Class="CheckBox1.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 Margin="50, 50, 50, 50" Name="cb1" FontSize="24" Checked="HandleChange">Check Box</CheckBox>
    </Grid>
</Window>
MainWindow.xaml.cs
using System.Windows;
using System.Windows.Controls;

namespace CheckBox1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void HandleChange(object sender, RoutedEventArgs e)
        {
            cb1.Content = "You clicked the check box";
        }
    }
}

We need to look at the click event handler HandleChange.  Once the checkbox is clicked, the text or content in the checkbox will be updated.

Here is the output:

checkbox1

Series Navigation<< WPF: WPF and XAML namespace declarations
WPF: Creating a checkbox control using code >>

Leave a comment

Leave a Reply