PropertyGrid 显示动态自定义属性

如果让 PropertyGrid 显示自定义的动态生成的Properties ?

用 PropertyGrid 显示一个固定类的 Properties 很简单,只需要用 PropertyGrid 的 SelectedObject 就行。

但是有些情况,需要 PropertyGrid 显示一些动态的,自定义的 Properties,可以免去写很多类的工作。比如说,你有很多配置文件,都需要用PropertyGrid 显示,如果死做,就要为每个配置文件编写一个类,太麻烦,而且万一又有新的配置文件,又得新写一个类。

要解决这个问题,让所有配置文件(当然得符合一定的要求)都可以通过 PropertyGrid 显示,方法如下:

1. PropertyGrid 需要有一个 SelectedObject,为此,写一个类 (姑且叫 Class1),作为 PropertyGrid 的 SelectedObject,这个类要 Implements ICustomTypeDescriptor
Imlements 之后,会有一堆属性和方法要实现,最重要的是

Public Function GetProperties(ByVal attributes() As System.Attribute) _
As System.ComponentModel.PropertyDescriptorCollection _
Implements System.ComponentModel.ICustomTypeDescriptor.GetProperties
... '在此编写代码
End Function

其实 ProperGrid 显示的 Properties,就是 System.ComponentModel.PropertyDescriptorCollection

2. 如何生成 PropertyDescriptorCollection,来传给类 Class1 呢?

先说传,这很简单,在 Class1 New 的时候,传一个对象 (姑且叫做Class2)作为参数,该 Class2 包含一个属性为PropertyDescriptorCollection 类型就行。

要生成 PropertyDescriptorCollection,我们得先说如何生成一个单个的 PropertyDescriptor。单个的 PropertyDescriptor 能生成了,PropertyDescriptorCollection 生成就不难。

Class2 负责生成 PropertyDescriptorCollection。

3. 如何生成一个单个的 PropertyDescriptor?
写一个类(姑且叫做Class3),让这个类 Inherits PropertyDescriptor。Class3 负责生成单个的 PropertyDescriptor。

这个类需要Overrides 不少 Property 和 Method。

为了让 Class 3 有数据支持,在New Class3 时传一个参数 Class4,Class 4 含有 Class3 所需要具体数据。

大致就是这样。


编者或作者: 我有闲    收录日期: 2008-12-19
参考或来源:

上一页: PropertyGrid控件(9) 自定义 UITypeEditor 返回上级目录: IT知识文章 下一页: rel="external" 和 rel="nofollow" 的用途


© 2008 woyouxian.net 版权所有 Contact Us