zoukankan      html  css  js  c++  java
  • 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; }
        }
  • 相关阅读:
    正则表达式例子
    addevent兼容函数 && 阻止默认行为 && 阻止传播
    addevent
    区分总结innerHeight与clientHeight、innerWidth与clientWidth、scrollLeft与pageXOffset等属性
    setattribute兼容
    随机分配位置
    浏览器类型
    统计一个字符串中相同字符的个数
    Appium发送中文或其他语言的问题
    Appium同时连接多台手机进行测试(多线程)
  • 原文地址:https://www.cnblogs.com/wq352/p/8794647.html
Copyright © 2011-2022 走看看