Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My checkbox returns NULL when unchecked

Tags:

binding

wpf

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
}
like image 646
seekle Avatar asked Jul 07 '11 17:07

seekle


People also ask

How do you send a value for a checkbox when it is unchecked?

If you wanted to submit a default value for the checkbox when it is unchecked, you could include an <input type="hidden"> inside the form with the same name and value , generated by JavaScript perhaps.

How do you keep a checkbox valued?

In the case of a "checkbox", you have to actually modify the <input> to include the keyword "checked". Similarly for "options" and "text". For "text" you fill in the "value=" after suitably escaping the text (using htmlentities() ).

Can checkbox be null?

The value of a checkbox is true or false, 1 or 0, there is no null. Hi Mike, Unfortunately not! It's a true/false type means it's a Boolean it will return 0 or 1 only and you can not define anything more than this.

How do I keep a checkbox checked by default?

The Input Checkbox defaultChecked property in HTML is used to return the default value of checked attribute. It has a boolean value which returns true if the checkbox is checked by default, otherwise returns false.


1 Answers

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.

like image 93
Kent Boogaart Avatar answered Oct 01 '22 03:10

Kent Boogaart