如何在IValueConverter中使用targetType参数?

时间:2022-12-27 09:11:33

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

我有一个IValueConverter,我想用它做一个简单的数学,具有以下转换函数:

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.

显然这对每种情况都不起作用,因为某些属性是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.

我知道targetType参数很可能是我需要在这个转换器中使用的,但我没有找到如何正确使用它来将返回值转换为相应需要的示例。

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

有谁知道如何在此上下文中使用targetType参数?

2 个解决方案

#1


4  

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);
}

#2


1  

you can do this

你可以这样做

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

if(typeCode  == TypeCode.Int32)
{
  // it is int type
}

#1


4  

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);
}

#2


1  

you can do this

你可以这样做

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

if(typeCode  == TypeCode.Int32)
{
  // it is int type
}