使枚舉類型的選項在VS的屬性窗裏顯示爲中文
我們自己做的組件,一般希望它的屬性在設計時能夠在屬性窗裏顯示爲中文,可以在屬性上添加System.ComponentModel.DisplayNameAttribute標註達到這個目的。但是,枚舉的選項如何以中文的形式顯示在屬性窗裏呢?
假設我們有如下枚舉:
1: public enum MyEnum
2: {
3: A,
4: B
5: }
在某個組件裏有一個MyEnum類型的屬性,如下:
1: [DisplayName("我的枚舉")]
2: public MyEnum MyEnum
3: {
4: get;set;
5: }
在設計時把這個組件拖到設計器中,發現屬性窗中出現了“我的枚舉”這個屬性,但選項是A和B,如何讓它們示爲“選項一”和“選項二”呢?這就需要利用到TypeConverter了,因爲PropertyGrid利用TypeConverter來顯示枚舉的選項的。另外,爲了使擴展性更好,我們還需要DescriptionAttribute.
繼承System.ComponentModel.EnumConverter,實現自己的Converter,如下:
1: public class MyEnumConverter : EnumConverter
2: {
3: private IDictionary<object, string> dic;
4: private IDictionary<string, object> dic2;
5: private readonly Type type = typeof(MyEnum);
6:
7: public MyEnumConverter()
8: : base(typeof(MyEnum))
9: {
10: }
11:
12:
13: public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
14: {
15: if(value is string)
16: {
17: if(dic2 != null && dic2.ContainsKey(value as string))
18: {
19: return dic2[value as string];
20: }
21: }
22: return base.ConvertFrom(context, culture, value);
23: }
24:
25: public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
26: {
27: if(destinationType == typeof(string))
28: {
29: if(dic == null)
30: {
31: dic = new Dictionary<object, string>();
32: dic2 = new Dictionary<string, object>();
33: Type reflectionType = TypeDescriptor.GetReflectionType(this.type);
34: if (reflectionType == null)
35: {
36: reflectionType = this.type;
37: }
38: FieldInfo[] fields = reflectionType.GetFields(BindingFlags.Public | BindingFlags.Static);
39: ArrayList list = null;
40: if ((fields != null) && (fields.Length > 0))
41: {
42: list = new ArrayList(fields.Length);
43: }
44: if (list != null)
45: {
46: foreach (FieldInfo info in fields)
47: {
48: object fieldValue = info.GetValue(info);
49: string desc = fieldValue.ToString();
50: DescriptionAttribute descriptionAttribute = null;
51: foreach (DescriptionAttribute a in info.GetCustomAttributes(typeof(DescriptionAttribute), false))
52: {
53: descriptionAttribute = a;
54: break;
55: }
56: if (descriptionAttribute != null)
57: {
58: desc = descriptionAttribute.Description;
59: }
60: dic[fieldValue] = desc;
61: dic2[desc] = fieldValue;
62: }
63: }
64: }
65: return dic[value];
66: }
67:
68: return base.ConvertTo(context, culture, value, destinationType);
69: }
70: }
然後修改MyEnum,如下:
1: public enum MyEnum
2: {
3: [Description("選項一")]
4: A,
5: [Description("選項二")]
6: B
7: }
並且修改組件裏的屬性,加入TypeConverterAttribute,如下:
1: [DisplayName("我的枚舉")]
2: [TypeConverter(typeof(MyEnumConverter))]
3: public MyEnum MyEnum
4: {
5: get;
6: set;
7: }
這樣,就可以以中文的形式在屬性窗裏顯示枚舉的選項了,如下圖:
出處:http://www.cnblogs.com/default
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接,否則保留追究法律責任的權利。