Wpf – Make checkbox bound to nullable bool transition from null to true

bindingcheckboxwpf

I have a checkbox with its IsChecked property bound to a nullable bool. When my control first loads the value is null and the checkbox appears greyed out. This is what I want.

When the user clicks the checkbox, it moves to the false/Unchecked state.

However, 99% of the time the user is going to want to tick the checkbox – which currently means double clicking the checkbox.

How can I make the value move from null to true when the user first clicks the checkbox?

Best Answer

You can just modify the setter of the bound property to check whether the previous value is null and if it is, set the value to true. Something like this:

public bool? MyBoolProperty 
{
   get { return _myBoolProperty; }
   set 
   {
       _myBoolProperty = (_myBoolProperty != null || value == null) ? value : true;
       RaisePropertyChanged("MyBoolProperty");       
   }
}

The binding system will re-read the property after it sets it, so the new value will be reflected by the CheckBox.