要在PropertyGrid中自定義屬性顯示,您需要遵循以下步驟:
Person
的類(lèi),其中包含Name
和Age
屬性:public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
CategoryAttribute
、DisplayNameAttribute
和DescriptionAttribute
等特性。將這些特性添加到您的類(lèi)屬性中,以便在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; }
}
在您的窗體上添加一個(gè)PropertyGrid控件。在本例中,我們將其命名為propertyGrid1
。
在窗體的Load
事件中,將Person
對(duì)象分配給propertyGrid1
的SelectedObject
屬性:
private void Form1_Load(object sender, EventArgs e)
{
Person person = new Person { Name = "John Doe", Age = 30 };
propertyGrid1.SelectedObject = person;
}
現(xiàn)在,當(dāng)您運(yùn)行應(yīng)用程序時(shí),PropertyGrid將顯示自定義屬性名稱(chēng)、類(lèi)別和描述。您可以根據(jù)需要修改這些特性以更改屬性的顯示方式。