Tuesday 26 April 2011

WPF Binding Controls

Tried binding some checkboxes to a "check all" checkbox as below and it worked fine except that when a bound checkbox is clicked the binding gets lost. Not what I was intending but apparently this is how 'OneWay' binding behaves. There were some workarounds but I thought it easier in the end to do what I wanted without binding and instead to add good old-fashioned "Checked" and "Unchecked" event handlers to the "check all" checkbox.

Code I was using before...
Binding binding_isChecked = new Binding("IsChecked");
binding_isChecked.ElementName = "cbCheckAll";
binding_isChecked.Mode = BindingMode.OneWay;
DependencyProperty property_isChecked = CheckBox.IsCheckedProperty;

Binding binding_isNotChecked = new Binding("IsChecked");
binding_isNotChecked.ElementName = "cbCheckAll";
binding_isNotChecked.Mode = BindingMode.OneWay;
BoolToOppositeBoolConverter boolConverter = new BoolToOppositeBoolConverter();
binding_isNotChecked.Converter = boolConverter;
DependencyProperty property_isEnabled = CheckBox.IsEnabledProperty;

cb.SetBinding(property_isChecked, binding_isChecked);
cb.SetBinding(property_isEnabled, binding_isNotChecked);
Code I'm using now...
cb.Checked += delegate
{
foreach (CheckBox checkBoxInStackPanel in sp.Children)
{
if (!checkBoxInStackPanel.Content.Equals(cbCheckAllContent))
{
checkBoxInStackPanel.IsChecked = true;
checkBoxInStackPanel.IsEnabled = false;
}
}
};

cb.Unchecked += delegate
{
foreach (CheckBox checkBoxInStackPanel in sp.Children)
{
if (!checkBoxInStackPanel.Content.Equals(cbCheckAllContent))
{
checkBoxInStackPanel.IsChecked = false;
checkBoxInStackPanel.IsEnabled = true;
}
}
};