0

I'm using WPF and i have a converter i use with multibinding for substraction. In this converter i simple do values[0]-values1, however before doing that i need to convert the data to the same data type like so:

    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values[0] is short)
        {
            return (short)values[0] - (short)values[1];
        }
        if (values[0] is float)
        {
            return (float)values[0] - (float)values[1];
        }
        if (values[0] is double)
        {
            return (double)values[0] - (double)values[1];
        }
        return (int)values[0] - (int)values[1];
    }

However, a problem occurs when i try to convert an System.Int32 to double when passed through .xaml without a binding/path/reference/resource;

                        <TextBox.Width>
                            <MultiBinding Converter="{StaticResource Subtraction}">
                                <Binding Path="ActualWidth" ElementName="b"/>
                                <Binding>
                                    <Binding.Source>
                                        <sys:Int32>17</sys:Int32>
                                    </Binding.Source>
                                </Binding>
                            </MultiBinding>

sys is: xmlns:sys="clr-namespace:System;assembly=mscorlib"

So i did some testing by adding this to the converter:

enter image description here

Which gives me these results, notice "test" and "values1" are both the exact same data type (System.Int32) yet they behave differently. One causes an error, the other not. What is the difference?

Using System.Convert.ToDouble() instead of casting with (double) resolved the problem. But i still want to know why the other way didnt work. Shouldnt a Int32 and another Int32 behave exactly the same? What could be the underlaying cause for the different behaviour?

Clemens
  • 123,504
  • 12
  • 155
  • 268
morknox
  • 87
  • 8

1 Answers1

0

Values is an array of boxed objects. The objects need to be unboxed first before i can convert the data type.

Since values[1] is an int, you first need to unbox it with (int), then after you can convert the int to double.

 (double)(int)values[1]

However, this will only work if the data type that is boxed into values[1] is an integer. So for that reason using System.Convert.ToDouble() is preferable.

More explaination for boxed values: Why do we need boxing and unboxing in C#?

morknox
  • 87
  • 8