PropertyGrid中的枚举显示为中文

参考http://www.cnblogs.com/yank/archive/2011/09/17/2179598.html

在上述文档的基础上做了改进。从EnumConverter类派生

显示效果:

1、定义枚举:在枚举中加入描述信息,作为我们需要显示的信息;

enum MediaType
    {
        [Description("文本")]
        Text = 0,
        [Description("图片")]
        Image = 1,
        [Description("视频")]
        Video = 2     
    }

2、定义TypeConverter,对枚举进行转换;

class EnumTypeConverter:EnumConverter
    {
        private Type _enumType;

        public EnumTypeConverter(Type type): base(type)
        {
            _enumType = type;
        }

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

        public override object ConvertTo(ITypeDescriptorContext context,CultureInfo culture,object value, Type destType)
        {
            FieldInfo fi = _enumType.GetField(Enum.GetName(_enumType, value));
            DescriptionAttribute da =(DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));

            if (da != null)
                return da.Description;
            else
                return value.ToString();
        }

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

        public override object ConvertFrom(ITypeDescriptorContext context,CultureInfo culture,object value)
        {
            foreach (FieldInfo fi in _enumType.GetFields())
            {
                DescriptionAttribute da =(DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));

                if ((da != null) && ((string)value == da.Description))
                    return Enum.Parse(_enumType, fi.Name);
            }
            return Enum.Parse(_enumType, (string)value);
        }
    }

3、属性使用TypeConverter;

class MediaInfo
    {

        [Category("媒体类型"), DisplayName("名称"), Description("Media Type")]
        public string MediaName { get; set; }

        [DisplayName("媒体类型"), Description("Media Type")]
        [Category("媒体类型"),TypeConverter(typeof(EnumTypeConverter))]
        public MediaType MediaTypeDisplay { get; set; }
                
        public int ID { get; set; }
    }

 

posted @ 2018-04-11 11:26  Joan2016  阅读(1169)  评论(0编辑  收藏  举报