开发者

My checkbox returns NULL when unchecked

开发者 https://www.devze.com 2023-03-18 13:55 出处:网络
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 val

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 con开发者_运维问答verter 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
}


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号