要以编程方式隐藏PropertyGrid中的字段,您需要使用BrowsableAttributes
属性来定制字段的可浏览性
using System;
using System.Windows.Forms;
namespace PropertyGridExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.propertyGrid1.SelectedObject = new CustomObject();
}
}
[DefaultProperty("Field2")]
public class CustomObject
{
private string field1 = "Field 1";
private string field2 = "Field 2";
[Browsable(false)]
public string Field1
{
get { return field1; }
set { field1 = value; }
}
public string Field2
{
get { return field2; }
set { field2 = value; }
}
}
}
在这个例子中,我们创建了一个名为CustomObject
的类,它有两个属性:Field1
和Field2
。我们使用[Browsable(false)]
属性来标记Field1
,使其在PropertyGrid中不可见。Field2
将保持可见,因为我们没有应用任何定制属性。
然后,我们将此类的实例设置为propertyGrid1
的SelectedObject
,以便在PropertyGrid中显示其属性。运行此代码后,您将看到PropertyGrid中仅显示Field2
属性。
领取专属 10元无门槛券
手把手带您无忧上云