How do I use the targetType parameter in an IValueConverter?
Asked Answered
I

2

7

I have an IValueConverter which I want to use for doing simple math that has the following Convert function :

public object Convert(
        object value,
        Type targetType,
        object parameter,
        CultureInfo culture)
    {
        if (parameter == null)
        {
            return value;
        }

        switch (((string)parameter).ToCharArray()[0])
        {
            case '%':
                return (double)value % double.Parse(
                    ((string)parameter).TrimStart(new char[] {'%'}));
            case '*':
                return (double)value * double.Parse(
                    ((string)parameter).TrimStart(new char[] {'*'}));
            case '/':
                return (double)value / double.Parse(
                    ((string)parameter).TrimStart(new char[] {'/'}));
            case '+':
                return (double)value + double.Parse(
                    ((string)parameter).TrimStart(new char[] {'+'}));
            case '-':
                if (((string)parameter).Length > 1)
                {
                    return (double)value - double.Parse(
                        ((string)parameter).TrimStart(new char[] {'-'}));
                }
                else
                {
                    return (double)value * -1.0D;
                }
            default:
                return DependencyProperty.UnsetValue;
        }
    }

Obviously this doesn't work for each case because some properties are of type int.

I know that the targetType parameter is likely what I need to use in this converter but I have found no examples of how to make proper use of it to convert the return value to what it needs to be accordingly.

Does anyone know how to use the targetType parameter in this context?

Ilysa answered 19/2, 2016 at 19:0 Comment(0)
B
8

This should work without too much overhead:

public object Convert(
    object value, Type targetType, object parameter, CultureInfo culture)
{
    double result = ... // your math

    return System.Convert.ChangeType(result, targetType);
}
Bodywork answered 19/2, 2016 at 19:34 Comment(0)
S
2

you can do this

var typeCode  = Type.GetTypeCode(targetType); // Pass in your target type

if(typeCode  == TypeCode.Int32)
{
  // it is int type
}
Sofia answered 19/2, 2016 at 19:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.