PropertyGrid控制元件下拉列表
阿新 • • 發佈:2019-02-09
1 ///<summary> 2 /// 一.自定義一個特性類ListAttribute,提供下拉列表值:
3 ///</summary> 4 publicclass ListAttribute : Attribute
5 {
6 publicstring[] _lst;
7 8 public ListAttribute(string[] lst)
9 {
10 //初始化列表值 11 _lst =lst;
12 }
13 }
14 15 ///<summary> 16 /// 二.特性轉換器MyConverter
17 ///</summary>18 publicclass MyConverter : ExpandableObjectConverter
19 {
20 publicoverridebool GetStandardValuesSupported(ITypeDescriptorContext context)
21 {
22 returntrue;
23 }
24 25 publicoverridebool GetStandardValuesExclusive(ITypeDescriptorContext context)
26 {
27 returntrue;
28 }
29 30 publicoverride StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
31 {
32 ListAttribute listAttribute = (ListAttribute)context.PropertyDescriptor.Attributes[typeof(ListAttribute)];
33 StandardValuesCollection vals =new TypeConverter.StandardValuesCollection(listAttribute._lst);
34 35 return vals;
36 }
37 38 publicoverridebool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
39 {
40 returntrue;
41 }
42 }
43 44 ///<summary>45 /// 三.應用示例:
46 ///</summary>47 publicclass MyObject
48 {
49 privatestring _name;
50 51 [CategoryAttribute("資訊"), DescriptionAttribute("姓名"),
52 TypeConverter(typeof(MyConverter)), ListAttribute(newstring[] { "張三", "李四", "王五", "趙六", "馬七" })]
53 publicstring Name
54 {
55 get { return _name; }
56 set { _name = value; }
57 }
58 }
59 60 privatevoid Form1_Load(object sender, EventArgs e)
61 {
62 this.propertyGrid1.SelectedObject =new MyObject();
63 }