namespace Yw.WinFrmUI { /// /// 枚举在propertyGrid中的显示 /// public class EnumPropertyConverter : ExpandableObjectConverter { /// /// 构造函数 /// public EnumPropertyConverter() { _dict = new Dictionary(); } private Dictionary _dict;//枚举项集合 /// /// 加载枚举项集合 /// private void LoadDict(ITypeDescriptorContext context) { _dict = GetEnumValueDispDict(context.PropertyDescriptor.PropertyType); } /// /// 是否可从来源转换 /// public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); } /// /// 从来源转换 /// public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value is string) { //如果是枚举 if (context.PropertyDescriptor.PropertyType.IsEnum) { if (_dict.Count <= 0) LoadDict(context); if (_dict.Values.Contains(value.ToString())) { foreach (object obj in _dict.Keys) { if (_dict[obj] == value.ToString()) { return obj; } } } } } return base.ConvertFrom(context, culture, value); } /// /// 是否可转换 /// public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return true; } /// /// /// public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } /// /// /// public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } /// /// /// public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { if (_dict == null || _dict.Count <= 0) LoadDict(context); StandardValuesCollection vals = new TypeConverter.StandardValuesCollection(_dict.Keys); return vals; } /// /// /// public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (_dict.Count <= 0) LoadDict(context); foreach (object key in _dict.Keys) { if (key.ToString() == value.ToString() || _dict[key] == value.ToString()) { return _dict[key].ToString(); } } return base.ConvertTo(context, culture, value, destinationType); } /// /// 记载枚举的值+Display /// /// /// public Dictionary GetEnumValueDispDict(Type enumType) { Dictionary dict = new Dictionary(); FieldInfo[] fieldinfos = enumType.GetFields(); foreach (FieldInfo field in fieldinfos) { if (field.FieldType.IsEnum) { Object[] objs = field.GetCustomAttributes(typeof(DisplayAttribute), false); if (objs.Length > 0) { dict.Add(Enum.Parse(enumType, field.Name), ((DisplayAttribute)objs[0]).Name); } } } return dict; } } }