Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueConverter for IsChecked property of WPF Toggle Button

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.

like image 939
Tom Davies Avatar asked Dec 13 '22 10:12

Tom Davies


1 Answers

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.

like image 50
Martin Hennings Avatar answered Jan 02 '23 21:01

Martin Hennings