Delphi 给自定义控件添加属性页

一、基础知识介绍:

1、属性编辑器和控件属性的关联函数:

RegisterPropertyEditor函数:它用来注册一个属性编辑器,将控件中的一个属性和编辑器关联起来。

procedure RegisterPropertyEditor(PropertyType: PTypeInfo; ComponentClass: TClass; const PropertyName:string; EditorClass: TPropertyEditorClass);

1>、PropertyType:PTypeInfo。它是一个指针,指向要编辑的属性的运行期类型信息。我们通过TypeInfo()获取(TypeInfo(string))。

2>、Component: Calss。用于指定这个属性编辑器所作用的组件类(TMyDataBaseEdit);

3>、const PropertyName: string。是一个字符串,用于指定被作用属性的名称。

4>、EditorClass: TPropertyEditorClass。用于指定属性编辑器的类型。

利用RegisterPropertyEditor函数,就可以把一个组件分成两个包:一个设计期包和一个运行期包,减少代码的膨胀。

二、创建设计包:

在自定义控件添加一列属性,在属性编辑浏览器中出现一项属性(XAbout),右侧显示:(XAbout)… ,点击“…”按钮弹出一个对话框。

具体步骤:

1、 下面我们开始新建一个Package,按照命名规则起名:MyDataEditDsgn60.Dpk,

2、 然后新建一个Form(TFrmAbout),作为XAbout对话框,我们可以根据需要自行设计界面。

3、 在MyDataEditDsgn60.Dpk的requires后面加上:DesignIDE。(不然可能会遇到问题“File not found Proxies.dcu”)

4、 在TFrmAbout窗体类的下面新建一个类TAboutEditor,使其从TPropertyEditor下继承过来:

TAboutEdit = class(TPropertyEditor) //属性编辑器。Uses DesignEditors;

private

FFrmAbout: TFrmAbout;

public

function GetAttributes: TPropertyAttributes;override; //Uses DesignIntf

function GetValue: string;override;// 覆盖GetAttributes函数:告诉IDE将以何种工作方式进行显示

procedure Edit;override;// 覆盖Edit函数:用来创建销毁窗体对象。

end;

注意:将全局的变量(FrmAbout: TFrmAbout)删掉,重新在TAboutEdit类中声明一个新的私有变量。

5、实现各个控制函数函数:( 如果想进一步控制,还可以在研究TPropertyEditor类的代码)

1>、覆盖Edit函数:用来创建销毁窗体对象。

procedure TAboutEdit.Edit;

begin

FFrmAbout := TfrmAbout.Create(Application);

FFrmAbout.ShowModal;

FreeAndNil(FFrmAbout);

end;

2>、覆盖GetAttributes函数:告诉IDE将以何种工作方式进行显示

function TAboutEdit.GetAttributes: TPropertyAttributes;

begin

Result := [paDialog,paReadOnly];//以只读对话框的方式显示的

end;

关于TPropertyAttributes可以参考帮助看看。我们这里是以只读对话框的方式显示的,【ObjectInspector】将在About属性旁边出现一个省略号按钮。当用户单击这个按钮,就调用Edit方法。

3>、覆盖GetValue函数,是为了省略号按钮旁出现“(About)”的字样,并且只读。

function TAboutEdit.GetValue: string;

begin

Result := '(About)'

end;

三、把上面的编辑器和控件关联起来

1、在窗体TFrmAbout的单元文件里添加注册属性的代码;

1>、在implementation的前面添加代码: procedure Register; //注册构件

2>、在implementation的后面添加代码:

procedure Register;

begin

//前提是组件面板中已经存在TMyDataBaseEdit自定义控件,它存在XAbout这个属性,属性类型为String型;

//将TAboutEdit与属性XAbout关联起来

RegisterPropertyEditor(TypeInfo(string),TMyDataBaseEdit,'XAbout',TAboutEdit);

end;

假如第二个参数设为nil,第三个参数设为空串,RegisterPropertyEditor(TypeInfo(string),nil,'',TAboutEdit);所有string类型的属性全部变成About框了。(呵呵,理论上是这么回事,但是实际上根本不是。) 把窗体TFrmAbout做成一个复杂的有返回值的对话框,这样我们就可以真正用对话框来编辑控件的属性了。

Delphi 制作自定义数据感知控件并装入包(dpk文件)中(与DBText类似的数据感知控件)