65.9K
CodeProject 正在变化。 阅读更多。
Home

在运行时向 PropertyGrid 添加(删除)项

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.79/5 (46投票s)

2005年1月12日

1分钟阅读

viewsIcon

199028

downloadIcon

6049

在运行时修改 PropertyGrid 控件的项目集合。

Sample Image - Dynamic_Propertygrid.jpg

引言

希望您熟悉 Windows PropertyGrid 控件。我很久以前使用过这个控件,但没有机会处理动态属性。我以为会有一些像 GridName.Items.Add() 这样的方法可以在运行时添加项目。但是,我不得不编写一些代码来实现相同的功能。我的需求很简单:我想在 PropertyGrid 中显示我的对象的全部属性,但我不知道设计时属性的名称。我使用了 CollectionBaseICustomTypeDescriptorPropertyDescriptor 类来实现相同的功能。

自定义属性

首先,我创建了一个具有以下公共属性的 CustomProperty

  • 名称
  • ReadOnly
  • Visible

构造函数如下所示

public CustomProperty(string sName, 
          object value, bool bReadOnly, bool bVisible )
{
 this.sName = sName;
 this.objValue = value;
 this.bReadOnly = bReadOnly;
 this.bVisible = bVisible;
}

自定义 PropertyDescriptor

下一步是为我的类创建一个 PropertyDescriptor。从 PropertyDescriptor 类派生 CustomPropertyDescriptor

public class CustomPropertyDescriptor: PropertyDescriptor
{
 CustomProperty m_Property;
 public CustomPropertyDescriptor(ref CustomProperty myProperty, 
             Attribute [] attrs) :base(myProperty.Name, attrs)
 {
  m_Property = myProperty;
 }
 .....

由于它是一个抽象类,我们必须重写 PropertyDescriptor 的所有方法。

自定义类

我们将创建此 CustomClass 的对象,用于 PropertyGrid.SelectedObject

 public class CustomClass: CollectionBase,ICustomTypeDescriptor
{
  
 public void Add(CustomProperty Value)
 {
  base.List.Add(Value);
 }
  
 public void Remove(string Name)
 {
  foreach(CustomProperty prop in base.List)
  {
   if(prop.Name == Name)
   {
    base.List.Remove(prop);
    return;
   }
  }
 }
  
 public CustomProperty this[int index] 
 {
  get 
  {
   return (CustomProperty)base.List[index];
  }
  set
  {
   base.List[index] = (CustomProperty)value;
  }
 }
.......

这里是最重要的方法 GetProperties,它将在将对象绑定到 PropertyGrid 时被调用。

 public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
 PropertyDescriptor[] newProps = new PropertyDescriptor[this.Count];
 for (int i = 0; i < this.Count; i++)
 {
  CustomProperty  prop = (CustomProperty) this[i];
  newProps[i] = new CustomPropertyDescriptor(ref prop, attributes);
 }
  return new PropertyDescriptorCollection(newProps);
}

如何使用 CustomClass

CustomClass 可以在任何具有 PropertyGrid 的 Windows 窗体中使用。

CustomClass myProperties = new CustomClass();
propertyGrid1.SelectedObject = myProperties;
......

CustomProperty myProp = new CustomProperty(txtName.Text,txtValue.Text, 
                           chkReadOnly.Checked,true);
myProperties.Add(myProp);
propertyGrid1.Refresh();

最后

我希望用户能够扩展我的 CustomClass 并使用 PropertyGrid 控件处理动态属性。

© . All rights reserved.