Reputation: 2446
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.
Upvotes: 4
Views: 3250
Reputation: 9565
IsChecked is a nullable boolean. So instead of Boolean
, check for bool?
Upvotes: 3
Reputation: 29073
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.
Upvotes: 2
Reputation: 185583
This is as expected; IsChecked
is a bool?
, not a bool
. Change your first line to this:
if (targetType != typeof(bool?))
Upvotes: 3
Reputation: 16846
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:
ToggleButton Class
Base class for controls that can switch states, such as CheckBox.
and for IsChecked:
Property Value
Type: System.Nullable<Boolean>
true if the ToggleButton is checked; false if the ToggleButton is unchecked; otherwise null. The default is false.
So if you cast to a bool?
or Nullable, you can easily get the value with .HasValue
and .Value
.
Upvotes: 5