#351 – Binding a CheckBox’s IsChecked Property to a Boolean Variable

Instead of handling the Checked and Unchecked events of a CheckBox and then setting a boolean variable to represent the current state, you’ll most often just use data binding to bind the IsChecked property to a boolean variable.

In the example below, we have three CheckBox controls, each bound to a boolean property.

        <Label Content="Things my dog can do:"/>
        <CheckBox Content="Sit" IsChecked="{Binding CanSit}"/>
        <CheckBox Content="Stay" IsChecked="{Binding CanStay}"/>
        <CheckBox Content="Fetch" IsChecked="{Binding CanFetch}"/>
        <Button Content="Test" Click="Test_Click"/>

In the code-behind, we define the boolean properties that we can bind to and then set the data context to refer to the parent class.

        public bool CanSit { get; set; }
        public bool CanStay { get; set; }
        public bool CanFetch { get; set; }

		public MainWindow()
            this.DataContext = this;

        private void Test_Click(object sender, RoutedEventArgs e)
            MessageBox.Show(string.Format("Sit: {0}, Stay: {1}, Fetch: {2}", CanSit, CanStay, CanFetch));


About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

5 Responses to #351 – Binding a CheckBox’s IsChecked Property to a Boolean Variable

  1. Oto says:

    Thanks a lot man, you saved my diploma right now đŸ™‚

  2. Thank yuo for this simple tutorial.
    What is the simplest way to make this twoway binding? I can’t seem to be able to wrap my head around twoway binding.

    • Sean says:

      This example shows one-way binding, from the View to the code. Remember that if you want a change in the code to be reflected in the View, your class will need to implement INotifyPropertyChanged and fire a PropertyChanged event whenever the property value changes. You can’t do this with auto implemented properties, so you’ll need to add a backing variable and implemented the property getters/setters yourself.

    • Sean says:

      Example coming this Wednesday that will demonstrate two-way binding to a CheckBox.

  3. Pingback: #825 – Two Way Binding for a CheckBox | 2,000 Things You Should Know About WPF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: