WPF切换按钮IsChecked属性的ValueConverter

WPF切换按钮IsChecked属性的ValueConverter,wpf,data-binding,ivalueconverter,Wpf,Data Binding,Ivalueconverter,我正在尝试编写一个值转换器,用于将WPF ToggleButton的Boolean IsChecked属性绑定到模型中的非布尔值(碰巧是双精度值)。我编写的convert函数如下所示: public object Convert(object value, Type targetType, object paramter, System.Globalization.CultureInfo culutre) { if (targetType !=

我正在尝试编写一个值转换器,用于将WPF ToggleButton的Boolean IsChecked属性绑定到模型中的非布尔值(碰巧是双精度值)。我编写的convert函数如下所示:

        public object Convert(object value, Type targetType, object paramter, System.Globalization.CultureInfo culutre)
        {
          if (targetType != typeof(Boolean))
            throw new InvalidOperationException("Target type should be Boolean");

          var input = double.Parse(value.ToString());

          return (input==0.0) ? false: true;
        }
问题是当调用函数时,targetType不是我所期望的-它是

            "System.Nullable`1[[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"
而不是System.Boolean。这是预期的吗?我以前写过其他转换器,没有任何麻烦。

是的,因为切换按钮(想想复选框)可以有三种状态:选中、未选中和均不选中(复选框将灰显)

委员会:

以及:

属性值
类型:System.Nullable
如果选中了ToggleButton,则为true;如果未选中ToggleButton,则为false;否则为空。默认值为false。
因此,如果您强制转换为
bool?
或null,您可以使用
.HasValue
.value
轻松获得值,这与预期相符;是
bool?
,不是
bool
。将第一行更改为:

if (targetType != typeof(bool?))

是的,IsChecked是一个“可为空”的布尔值。。。这意味着它可以是真的、假的或空的。这里很少有带有null值的切换按钮,但在一些子类(如CheckBox)中更常见。

是一个可为null的布尔值。因此,不要选择
Boolean
,而是选择
bool?

+1来提及.HasValue。当我第一次开始使用可为null的类型时,我遇到了麻烦,因为我访问Value时没有检查HasValue@_@
Property Value
Type: System.Nullable<Boolean>
true if the ToggleButton is checked; false if the ToggleButton is unchecked; otherwise null. The default is false.
if (targetType != typeof(bool?))