Rac*_*hel 10 c# wpf enums converter datatrigger
我想能说
<DataTrigger Binding="{Binding SomeIntValue}" 
             Value="{x:Static local:MyEnum.SomeValue}">
并让它解决,就True好像int值等于(int)MyEnum.Value
我知道我可以Converter返回(MyEnum)intValue,但是我必须为我在DataTriggers中使用的每个Enum类型创建一个转换器.
有没有一种通用的方法来创建一个能够提供这种功能的转换器?
Dre*_*kes 10
可以以可重用的方式在枚举值及其底层整数类型之间创建转换器 - 也就是说,您不需要为每个枚举类型定义新的转换器.有提供足够的信息Convert和ConvertBack对本.
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);
    }
}
调用时,此转换器将纯粹基于value和targetType值在int/enum值之间翻转值的类型.没有硬编码的枚举类型.
我想我想通了
我只需要设置我的ConverterParameter而不是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;
}
| 归档时间: | 
 | 
| 查看次数: | 6205 次 | 
| 最近记录: |