seekle
seekle

Reputation: 228

My checkbox returns NULL when unchecked

I have the following code in my XAML file, with a very simple checkbox. When the checkbox is checked, it is setting my property to be true. However, when I uncheck the checkbox, I could see that the value is null, when debugging with a break point in the convertBack function. I even tried to set IsThreeState = false, but still not working. Anyone knows why?

<Window.Resources>
    <this:DebugValueConverter x:Key="debugConverter"/>
</Window.Resources>
<StackPanel>
 <CheckBox Content="Testing" IsThreeState="False"
                           IsChecked="{Binding CheckBoxValue, 
                                       Converter={StaticResource debugConverter},
                                       FallbackValue=false,TargetNullValue=false}"
                        />
</StackPanel>

The CheckBoxValue is a bool property in my view model.

The converter class is: public class DebugValueConverter : IValueConverter { #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value;
    }

    #endregion
}

Upvotes: 5

Views: 3517

Answers (2)

Kent Boogaart
Kent Boogaart

Reputation: 178770

It's simply because you have TargetNullValue=false on your Binding. That means a value of false from your CheckBoxValue property will be translated to null, which is what your converter sees.

Upvotes: 8

Ed Bayiates
Ed Bayiates

Reputation: 11230

IsChecked is often null even when your CheckBox isn't three state. Either bind to a bool? and use (foo == true) to avoid the null, or bind to a bool and use a converter which converts from bool? to bool by treating null as false.

Upvotes: 0

Related Questions