WPF 切换按钮的 IsChecked 属性的 ValueConverter
我正在尝试编写一个值转换器,用于将 WPF ToggleButton 的布尔 IsChecked 属性绑定到模型中的非布尔值(恰好是双精度值)。我编写的转换函数如下所示:
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。这是预期的吗?我过去编写过其他转换器,没有遇到任何麻烦。
I'm trying to write a Value converter to use to bind the Boolean IsChecked property of a WPF ToggleButton to a non Boolean value (which happens to be a double) in my model. The convert function I've written looks like this:
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;
}
The problem is that when the funcion is invoked, the targetType is not what I expect - it's
"System.Nullable`1[[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"
Rather than System.Boolean. Is this expected? I've written other converters with no hassle in the past.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,因为 ToggleButton(类似于复选框)可以处于三种状态:选中、未选中和两者都不是(复选框将呈灰色)。
MSDN 库声明:
和 对于 IsChecked:
因此,如果您转换为a
bool?
或 Nullable,您可以使用.HasValue
和.Value
轻松获取值。Yes, since a ToggleButton (think of a checkbox) can be in three states: Checked, Unchecked and Neither (checkbox would be greyed out).
The MSDN library states:
and for IsChecked:
So if you cast to a
bool?
or Nullable, you can easily get the value with.HasValue
and.Value
.这正如预期的那样;
已检查
< /a> 是一个bool?
,而不是bool
。将第一行更改为:This is as expected;
IsChecked
is abool?
, not abool
. Change your first line to this:IsChecked 是一个可为 null 的布尔值。因此,不要检查
Boolean
,而是检查bool?
IsChecked is a nullable boolean. So instead of
Boolean
, check forbool?
是的,IsChecked 是一个“可为空”布尔值...这意味着它可以是 true、false 或 null。这里很少有带有空值的切换按钮,但在某些子类(如 CheckBox)上更常见。
Yes, IsChecked is a 'nullable' boolean... meaning it could be true, false, or null. It's pretty rare to have a toggle button with a null value here but more common on some of the subclasses like CheckBox.