WPF Check box: Check changed handling

David picture David · Mar 18, 2013 · Viewed 105.1k times · Source

In WPF data binding, I can bind the IsChecked property to some data, e.g. user setting, but I need to handle "CheckChanged" event, I know I can seperately handle Checked, Unchecked event, but is there any way to get notified when this value is changed?

<CheckBox Content="Case Sensitive" IsChecked="{Binding bSearchCaseSensitive,
          Source={x:Static Properties:Settings.Default}}" />

Note: I don't care if it is checked or unchecked. I just want to be notified when it is changed.

Answer

nvoigt picture nvoigt · Mar 18, 2013

That you can handle the checked and unchecked events seperately doesn't mean you have to. If you don't want to follow the MVVM pattern you can simply attach the same handler to both events and you have your change signal:

<CheckBox Checked="CheckBoxChanged" Unchecked="CheckBoxChanged"/>

and in Code-behind;

private void CheckBoxChanged(object sender, RoutedEventArgs e)
{
  MessageBox.Show("Eureka, it changed!");
}

Please note that WPF strongly encourages the MVVM pattern utilizing INotifyPropertyChanged and/or DependencyProperties for a reason. This is something that works, not something I would like to encourage as good programming habit.