是否可以编写一个自定义的 EnumConverter 来代替默认的 EnumConverter?

Eer*_*den 1 c# enums

是否可以为EnumConverter始终使用而不是默认值的枚举类型编写自定义EnumConverter

我希望在我的 XAML 代码中随处使用此转换器,而无需指定要使用的转换器(如果可能)

Eer*_*den 5

我找到了如何做到这一点 :-) 这会将这种类型的所有枚举转换为选定的字符串。

首先,我必须向我的枚举添加一个 TypeConverter 属性:

using System.ComponentModel;

namespace WpfTestTypeConverter
{
    [TypeConverter(typeof(DeviceTypeConverter))]
    public enum DeviceType
    {
        Computer,
        Car,
        Bike,
        Boat,
        TV
    }
}
Run Code Online (Sandbox Code Playgroud)

而且我还必须基于 EnumConverter 类编写一个转换器

using System;
using System.ComponentModel;
using System.Globalization;

namespace WpfTestTypeConverter
{
    public class DeviceTypeConverter : EnumConverter
    {
        public DeviceTypeConverter(Type type) : base(type)
        {
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            return (destinationType == typeof(string));
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (value is DeviceType)
            {
                DeviceType x = (DeviceType)value;

                switch (x)
                {
                    case DeviceType.Computer:
                        return "This is a computer";
                    case DeviceType.Car:
                        return "A big car";
                    case DeviceType.Bike:
                        return "My red bike";
                    case DeviceType.Boat:
                        return "Boat is a goat";
                    case DeviceType.TV:
                        return "Television";
                    default:
                        throw new NotImplementedException("{x} is not translated. Add it!!!");
                }
            }
            return base.ConvertFrom(context, culture, value);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这有效。有人对此解决方案有任何意见吗?

  • 您可能想要使用数据注释,然后您可以在枚举上放置描述标签并使用函数将标签拉出,而不是硬编码 switch 语句。 (2认同)