wpfxamarinxamarin.formsivalueconverterimultivalueconverter

Invalid Cast Exception in MultiValueConverter Xamarin/WPF


While developing a MultiValueConverter I ran into an odd error.

I am getting an 'Invalid Cast Exception' on the line:

int frameSize = (int)values[0] ; // <-- thows InvalidCast Exception

I honestly cannot determine why.

public class SizeConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values == null || values.Length <3 || values[2] == null || values[1] == null || values[0] == null)
            return 0;
        int numItems = (int)values[2];
        int separatorSize = (int)values[1]; 
        int frameSize = (int)values[0] ; // <-- thows InvalidCast Exception
        
        int totalSeparatorSize = (numItems - 1) * separatorSize;
        int remainingArea = frameSize - totalSeparatorSize;
        return remainingArea / numItems;
    }
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

I verified the received values[3] array in the Converter in immediate Window:

`{object[3]}
    [0]: 100
    [1]: 2
    [2]: 4`

Here is the calling code MSTest [TestClass]:

[TestClass]
public class TestConverters
{
    [DataRow(100, 2, 4)]
    [DataTestMethod]
    public void Test_Piece_Sizing(double frameSize, int separatorSize, int numItems)
    {
        var sizeConverter = new SizeConverter();
        object[] values = new object[] { frameSize, separatorSize, numItems };
        Assert.AreNotEqual(0,sizeConverter.Convert(values, typeof(int), null, System.Globalization.CultureInfo.CurrentCulture));
    }
}

==============================================================================

===================A N D T H E Repaired C O D E IS:========================

    public class SizeConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values == null || values.Length <3 || values[2] == null || values[1] == null || values[0] == null)
            return 0;
        int numItems = (int)values[2];
        int separatorSize = (int)values[1]; 
        double frameSize = System.Convert.ToDouble(values[0]) ;
        
        int totalSeparatorSize = (numItems - 1) * separatorSize;
        int remainingArea = System.Convert.ToInt32(frameSize) - totalSeparatorSize;
        return remainingArea / numItems;
    }
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Solution

  • In the test case frameSize is a double, not an int. Either change it to int or cast to double in your Convert method.