1.將Property Grid 控制項添加到工具箱中
由於預設情況下Property Grid 控制項沒有顯示在工具箱中所以需要手動添加。
圖1 將Property Grid添加到工具箱(在工具箱上右鍵選擇添加/移除項)
圖2 在自訂工具箱對話方塊中選中PropertyGrid控制項
2.編寫自訂類,並跟PropertyGrid控制項進行綁定
using System;
using System.ComponentModel;
namespace PropertyGridDemo
{
[DefaultPropertyAttribute("Name")]
public class Customer
{
private string name;
private string email;
private string mark;
[CategoryAttribute("使用者資訊"), DescriptionAttribute("設定消費者姓名")]
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
[CategoryAttribute("使用者資訊"), DescriptionAttribute("設定消費者Email地址")]
public string Email
{
get
{
return email;
}
set
{
email = value;
}
}
[CategoryAttribute("備忘"), DescriptionAttribute("備忘資訊")]
public string Mark
{
get
{
return mark;
}
set
{
mark = value;
}
}
public Customer()
{
}
}
}
首先定義自訂類型的時候要引用System.ComponentModel命名空間,將使用到該命名空間中的一些Attribute類,在上面的例子中主要使用了DefaultPropertyAttribute,CategoryAttribute和DescriptionAttribute三個Attribute。
DefaultPropertyAttribute 指定組件的預設屬性。
CategoryAttribute 指定當屬性或事件顯示在被一個設定為按分類順序模式的 System.Windows.Forms.PropertyGrid 控制項中時,用於給屬性或事件分組的類別的名稱。
DescriptionAttribute 指定屬性或事件的說明。
在編寫自定類的時候所有的屬性都應該有get 和set方法,如果沒有get方法那麼這個屬性在PropertyGrid中不顯示,沒有set方法的話則為唯讀屬性在PropertyGrid中無法設定該屬性的值。
將自訂類與PropertyGrid控制項進行綁定
使用PropertyGrid類的SelectedObject屬性進行綁定
private void Form1_Load(object sender, System.EventArgs e)
{
Customer customer = new Customer();
customer.Name = "張三";
customer.Email = "zhangsan@sina.com";
propertyGrid1.SelectedObject = customer;
}
運行結果: