是否可能创建一个通用的整数到枚举类型的转换器?

10

我想要能够说

<DataTrigger Binding="{Binding SomeIntValue}" 
             Value="{x:Static local:MyEnum.SomeValue}">

如果 int 值等于 (int)MyEnum.Value,则使它解决为 True

我知道我可以创建一个返回 (MyEnum)intValueConverter,但这样一来,我就必须为我在 DataTriggers 中使用的每个枚举类型都创建一个转换器。

有没有一种通用的方法可以创建一个转换器,以提供这种功能?

5个回答

13

通过一种可重用的方式,即不需要为每个枚举类型定义一个新转换器,可以创建枚举值和它们底层整数类型之间的转换器。 给出的信息足以让ConvertConvertBack实现此功能。

public sealed class BidirectionalEnumAndNumberConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return null;

        if (targetType.IsEnum)
        {
            // convert int to enum
            return Enum.ToObject(targetType, value);
        }

        if (value.GetType().IsEnum)
        {
            // convert enum to int
            return System.Convert.ChangeType(
                value,
                Enum.GetUnderlyingType(value.GetType()));
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // perform the same conversion in both directions
        return Convert(value, targetType, parameter, culture);
    }
}

当被调用时,此转换器根据valuetargetType值纯粹地在int/enum值之间翻转值的类型。没有硬编码的枚举类型。


5

我想我搞明白了

我只需要将我的ConverterParameter设置为我要查找的枚举,然后评估True/False,而不是将Value等于该枚举

<DataTrigger Value="True"
             Binding="{Binding SomeIntValue, 
                 Converter={StaticResource IsIntEqualEnumConverter},
                 ConverterParameter={x:Static local:MyEnum.SomeValue}}">

转换器

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

    if (parameter.GetType().IsEnum && value is int)
    {
        return (int)parameter == (int)value;
    } 
    return false;
}

4
你也可以反过来,使用自定义标记扩展将枚举转换为int类型的值。

示例

<DataTrigger Binding="{Binding Path=MyNumber}"
             Value="{Markup:EnumToInt {x:Static Visibility.Visible}}">

EnumToIntExtension

public class EnumToIntExtension : MarkupExtension
{
    public object EnumValue
    {
        get;
        set;
    }
    public EnumToIntExtension(object enumValue)
    {
        this.EnumValue = enumValue;
    } 
    public override object ProvideValue(IServiceProvider provider)
    {
        if (EnumValue != null && EnumValue is Enum)
        {
            return System.Convert.ToInt32(EnumValue);
        }
        return -1;
    }
}

我以前从未遇到过MarkupExtensions,谢谢!每天都在学习新东西 :) - Rachel
其实我也一样,我刚开始使用它们,它们非常方便 :) - Fredrik Hedblad

1

我们过去也想过几次这样做,因此我们构建了几个扩展方法(在 int、long 等上)来帮助我们。所有这些的核心都实现在一个单一的静态泛型 TryAsEnum 方法中:

    /// <summary>
    /// Helper method to try to convert a value to an enumeration value.
    /// 
    /// If <paramref name="value"/> is not convertable to <typeparam name="TEnum"/>, an exception will be thrown
    /// as documented by Convert.ChangeType.
    /// </summary>
    /// <param name="value">The value to convert to the enumeration type.</param>
    /// <param name="outEnum">The enumeration type value.</param>
    /// <returns>true if value was successfully converted; false otherwise.</returns>
    /// <exception cref="InvalidOperationException">Thrown if <typeparamref name="TEnum"/> is not an enum type. (Because we can't specify a generic constraint that T is an Enum.)</exception>
    public static bool TryAsEnum<TValue, TEnum>( TValue value, out TEnum outEnum ) where TEnum : struct
    {
        var enumType = typeof( TEnum );

        if ( !enumType.IsEnum )
        {
            throw new InvalidOperationException( string.Format( "{0} is not an enum type.", enumType.Name ) );
        }

        var valueAsUnderlyingType = Convert.ChangeType( value, Enum.GetUnderlyingType( enumType ) );

        if ( Enum.IsDefined( enumType, valueAsUnderlyingType ) )
        {
            outEnum = (TEnum) Enum.ToObject( enumType, valueAsUnderlyingType );
            return true;
        }

        // IsDefined returns false if the value is multiple composed flags, so detect and handle that case

        if( enumType.GetCustomAttributes( typeof( FlagsAttribute ), inherit: true ).Any() )
        {
            // Flags attribute set on the enum. Get the enum value.
            var enumValue = (TEnum)Enum.ToObject( enumType, valueAsUnderlyingType );

            // If a value outside the actual enum range is set, then ToString will result in a numeric representation (rather than a string one).
            // So if a number CANNOT be parsed from the ToString result, we know that only defined values have been set.
            decimal parseResult;
            if( !decimal.TryParse( enumValue.ToString(), out parseResult ) )
            {
                outEnum = enumValue;
                return true;
            }
        }

        outEnum = default( TEnum );
        return false;
    }

这个实现可以处理任何基础类型的枚举,以及使用 [Flags] 属性定义的枚举。


0
你可以对 int 值执行 ToString(),然后将其传递给静态的 Enum.Parse 或 Enum.TryParse 方法,该方法接受你关心的枚举类型并返回相应的值。
但这并不是完美的解决方案,因为它无法处理表示多个枚举值的二进制 ORing 的整数。

我怎样在 Converter 中获取枚举类型? - Rachel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接