Check the box associated with the bool null transition from null to true

I have a checkbox with a property IsCheckedrelated to nullable bool. When my control first loads a value, it is null and the checkbox is grayed out. This is what I want.

When the user clicks this checkbox, he goes into false / Unchecked state.

However, in 99% of cases, the user will want to check the box, which currently means double-clicking on the box.

How can I make a value move from zero to true when the user first clicks on this flag?

+3
source share
5 answers

, , , , true. - :

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

, CheckBox.

+5

, . , , :)

IsThreeState TargetNullValue

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

, . .

+5

Click :

private void CheckBox_Click(object sender, RoutedEventArgs e)
{
  CheckBox cb = sender as CheckBox;

  switch (cb.IsChecked) 
  {
    case null:
      cb.IsChecked = false;
      break;

    case true:
      cb.IsChecked = true;
      break;

    case false:
      if (cb.IsThreeState) {
        cb.IsChecked = null;
      } else {
        cb.IsChecked = true;
      }
      break;
  }

  e.Handled = true;

}
+3

. , . , IsChecked false ViewModel. wpf. , null IsChecked IsChecked false.

protected internal virtual void OnToggle()
{
    bool? flag;
    if (this.IsChecked == true)
    {
        flag = (this.IsThreeState ? null : new bool?(false));
    }
    else
    {
        flag = new bool?(this.IsChecked.HasValue);
    }
    base.SetCurrentValueInternal(ToggleButton.IsCheckedProperty, flag);
}

, CheckBox OnToggle :

protected override void OnToggle()
{
   bool? flag;
   if (this.IsChecked == true)
   {
       flag = this.IsThreeState ? null : new bool?(false);
   }
   else 
       flag = true;
   // what a pity this method is internal
   // actually you can call this method by reflection
   base.SetCurrentValueInternal(ToggleButton.IsCheckedProperty, flag);
}

:

protected override void OnToggle()
{
    if (this.IsChecked == null)
        this.IsChecked = false;
    base.OnToggle();
}
+1

- click true, null, flag .

0

All Articles