WPF: Creating a checkbox control using code

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

At times, you might find that it is faster to create a control such as a checkbox using code.

Here we illustrate a simple example using checkbox.

The following example also generates a CheckBox (cb), with a label CheckBox, and then adds the CheckBox as a child of a grid (grid1).

<Window x:Class="CheckBox2.MainWindow"
        Title="MainWindow" Height="350" Width="525">
    <Grid Name="grid1" Margin="100,100,100,100">

using System.Windows;
using System.Windows.Controls;

namespace CheckBox2
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
        public MainWindow()

            CheckBox cb = new CheckBox();
            cb.Content = "CheckBox";
            cb.FontSize = 24;

In creating the CheckBox, we can also format the fontsize of the checkbox label.  The same method can be used to create other controls such as radio button.



In line 5 in the XAML file, we have given a name grid1 to the Grid.  This is similar to instance name in C#.  You would probably see that in line 30 in the C# code, we use grid1 as an instance name directly.

It seems that we do not have to declare grid1 instance name and we can use it instantly.  This exactly is the case as we have already made the necessary declarations as shown in this earlier example.


Series Navigation<< WPF: A simple checkbox
WPF: Checkbox status >>

Leave a comment

Leave a Reply