#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.InitializeComponent();
            this.DataContext = this;
        }

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

Advertisement