#351 – Binding a CheckBox’s IsChecked Property to a Boolean Variable
July 27, 2011 5 Comments
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)); }
Thanks a lot man, you saved my diploma right now đŸ™‚
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.
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.
Example coming this Wednesday that will demonstrate two-way binding to a CheckBox.
Pingback: #825 – Two Way Binding for a CheckBox | 2,000 Things You Should Know About WPF