要在PropertyGrid中自定義屬性顯示,您需要遵循以下步驟:
Person的類,其中包含Name和Age屬性:public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
CategoryAttribute、DisplayNameAttribute和DescriptionAttribute等特性。將這些特性添加到您的類屬性中,以便在PropertyGrid中更改屬性的顯示方式。例如:using System.ComponentModel;
public class Person
{
[Category("General")]
[DisplayName("Full Name")]
[Description("The person's full name.")]
public string Name { get; set; }
[Category("General")]
[DisplayName("Age")]
[Description("The person's age in years.")]
public int Age { get; set; }
}
在您的窗體上添加一個PropertyGrid控件。在本例中,我們將其命名為propertyGrid1。
在窗體的Load事件中,將Person對象分配給propertyGrid1的SelectedObject屬性:
private void Form1_Load(object sender, EventArgs e)
{
Person person = new Person { Name = "John Doe", Age = 30 };
propertyGrid1.SelectedObject = person;
}
現在,當您運行應用程序時,PropertyGrid將顯示自定義屬性名稱、類別和描述。您可以根據需要修改這些特性以更改屬性的顯示方式。