`

关于PropertyGrid 下拉列表,C#实现,其实比较简单

阅读更多

一、自定义一个特性类 ListAttribute ,提供下拉列表值:

using System;

using System.Collections.Generic;

using System.Text; using System.Collections;

namespace PropertyGrid {

class ListAttribute : Attribute {

public string[] lists;

public ListAttribute() {

lists = new string[] { "A", "B", "C", "D", "E" };//如果要实现动态下拉列表,在此处初始化lists对象值

}

}

}

二、一时想不起来了,就叫它特性转换器MyConverter

using System;

using System.Collections.Generic;

using System.Text;

using System.ComponentModel;

namespace PropertyGrid {

class MyConverter : ExpandableObjectConverter {

public override bool GetStandardValuesSupported(ITypeDescriptorContext context) {

return true;

}

public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) {

return true;

}

public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) {

ListAttribute lst = (ListAttribute)context.PropertyDescriptor.Attributes[typeof(ListAttribute)]; StandardValuesCollection vals = new TypeConverter.StandardValuesCollection(lst.lists);

return vals;

}

public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {

return true;

}

}

}

三、应用示例:

using System;

using System.Collections.Generic;

using System.Text;

using System.ComponentModel;

namespace PropertyGrid {

class MyObject {

private int id;

public int ID {

get {

return id;

}

set {

id = value;

}

}

private string code;

public string Code {

get {

return code;

}

set {

code = value;

}

}

private string name;

[CategoryAttribute("信息"),DescriptionAttribute("名称"),TypeConverter(typeof(MyConverter)),ListAttribute()] public string Name {

get {

return name;

}

set {

name = value;

}

}

public MyObject() {

this.id = -1;

this.code = "";

this.name = "";

}

}

}

这句你不会忘记吧:propertyGrid1.SelectedObject = new MyObject();

Ok,搞定!

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics