Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make checkbox bound to nullable bool transition from null to true

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?

like image 284
Grhm Avatar asked Dec 03 '22 09:12

Grhm


2 Answers

I had the same problem and ran into this question. This is a late response but I think this is the best solution :)

With the help of IsThreeState and TargetNullValue you can accomplish this

 <CheckBox  IsThreeState="False" IsChecked="{Binding YOUR_NULLABLE_PROPERTY, TargetNullValue=false}" />

The only caveat is that it will toggle between null and true. There will never be a false value.

like image 92
Tono Nam Avatar answered Mar 17 '23 03:03

Tono Nam


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.

like image 32
Pavlo Glazkov Avatar answered Mar 17 '23 05:03

Pavlo Glazkov