在winform项目中用PropertyGrid显示、编辑集合的属性
在winform开发中,利用PropertyGrid控件来显示、编辑对象的属性是非常方便的。
本文以一个公司类为例来介绍在Visual Studio(C#)中用PropertyGrid显示和编辑集合的属性,其中,公司对象中包含员工对象的集合。
1 添加员工类
添加员工类,有姓名、性别和头发颜色属性
public class Employee
{
[Category("基本属性")]
[DisplayName("员工姓名")]
[Description("员工姓名")]
public string Name { get; set; }
[Category("基本属性")]
[DisplayName("姓别")]
[Description("姓别")]
public EnumGender Gender { get; set; }
}
public enum EnumGender
{
男=0,
女,
};
2 添加员工类集合
public class EmployeeCollection : CollectionBase
{
public Employee this[int index]
{
get { return (Employee)List[index]; }
}
public void Add(Employee emp)
{
List.Add(emp);
}
public void Remove(Employee emp)
{
List.Remove(emp);
}
}
3 添加员工集合编辑器类
public class EmployeeCollectionEditor : CollectionEditor
{
public EmployeeCollectionEditor(Type type)
: base(type)
{
}
protected override string GetDisplayText(object value)
{
Employee item = new Employee();
item = (Employee)value;
return base.GetDisplayText(string.Format("{0}", item.Name));
}
}
GetDisplayText方法获取在员工编辑器左侧那栏显示的字符
4 添加公司类
public class Company
{
[Category("基本属性")]
[DisplayName("公司名称")]
[Description("公司名称")]
public string Name { get; set; }
[Category("基本属性")]
[DisplayName("公司地址")]
[Description("公司地址")]
public string Address { get; set; }
private EmployeeCollection emCollection = new EmployeeCollection();
[Editor(typeof(EmployeeCollectionEditor), typeof(System.Drawing.Design.UITypeEditor))]
[Category("公司的员工")]
[DisplayName("公司员工")]
[Description("员工是公司的财富")]
public EmployeeCollection Employees
{
get { return emCollection; }
set { emCollection = value; }
}
5 在PropertyGrid中显示对象属性
在窗体上添加一个PropertyGrid控件,在窗体的Form1_Load事件中调用以下代码。
private void LoadProperty()
{
Employee a = new Employee();
a.Name = "樊大姐";
a.Gender = EnumGender.女;
a.HairColor = Color.Yellow;
Employee b = new Employee();
b.Name = "张小蛋";
b.Gender = EnumGender.男;
b.HairColor = Color.Black;
Company company = new Company();
company.Employees.Add(a);
company.Employees.Add(b);
company.Address = "北京";
company.Name = "100度";
this.propertyGrid2.SelectedObject = company;
}
6 获取编辑后的属性
private void button1_Click(object sender, EventArgs e)
{
Company company = (Company)this.propertyGrid2.SelectedObject;
MessageBox.Show("公司名称是: " + company.Name);
}
7 效果
(1)公司对象属性
(2)员工集合
(3)获取修改后的对象属性
资源下载地址PropertyGrid控件显示和编辑集合