在编写自己的控件过程中,在类中用__property定义的属性,系统会自动调用匹配的属性编辑器,如字符串、图片、字体等。当系统默认的属性编辑不符合应用的要求时,需要对属性编辑进行扩展。如需要选择一个文件或路径,此时VCL系统没有相应的编辑器。此时,只能通过继承TPropertyEditor类来进行扩展。
#include <designeditors.hpp>
#include <DesignIntf.hpp>
#include <vcleditors.hpp>
//继承属性编辑器类
class PACKAGE TMyPropertyEditor:public TPropertyEditor
{
public:
void __fastcall SetValue(const AnsiString Value);
AnsiString __fastcall GetValue();
TPropertyAttributes __fastcall GetAttributes();
void __fastcall Edit(void);
__fastcall TMyPropertyEditor(const _di_IDesigner ADesigner, int APropCount);
__fastcall ~TMyPropertyEditor();
};
//覆盖父类方法:设置属性值
void __fastcall TMyPropertyEditor::SetValue(const AnsiString Value)
{
((TGraphicButtonControl1 * )GetComponent(0))->UIPicturePath->UIPath = Value;
((TGraphicButtonControl1 * )GetComponent(0))->SetUIPicPath(ExtractFilePath(Value));
}
//---------------------------------------------------------------------------
//覆盖父类方法:获取属性值
AnsiString __fastcall TMyPropertyEditor::GetValue()
{
AnsiString tmpS=((TGraphicButtonControl1 * )GetComponent(0))->UIPicturePath->UIPath;
((TGraphicButtonControl1 * )GetComponent(0))->SetUIPicPath(ExtractFilePath(tmpS));
return tmpS;
}
//---------------------------------------------------------------------------
__fastcall TMyPropertyEditor::TMyPropertyEditor(const _di_IDesigner ADesigner,
int APropCount):TPropertyEditor(ADesigner,APropCount)
{
}
//---------------------------------------------------------------------------
__fastcall TMyPropertyEditor::~TMyPropertyEditor()
{
//TODO: Add your source code here
}
//---------------------------------------------------------------------------
//修改属性,弹出对话框
TPropertyAttributes __fastcall TMyPropertyEditor::GetAttributes()
{
return TPropertyAttributes()<<paDialog;
}
//---------------------------------------------------------------------------
//通过对话框修改属性
void __fastcall TMyPropertyEditor::Edit(void)
{
TOpenDialog * dg = new TOpenDialog(0);
if(dg->Execute())
{
((TGraphicButtonControl1 * )GetComponent(0))->UIPicturePath->UIPath = ExtractFilePath(dg->FileName);
((TGraphicButtonControl1 * )GetComponent(0))->SetUIPicPath(ExtractFilePath(dg->FileName));
}
}
//---------------------------------------------------------------------------
//将特殊的属性字段封装到一个VCL类中,才能在控件的Register()函数中注册
class TMyFile : public TPersistent
{
AnsiString FFilePath;//这是文件路径,我们要用到的扩展属性
public:
TMyFile()
{
;
}
__published:
__property AnsiString UIPath = {read = FFilePath,write = FFilePath};
};
控件的.cpp文件中注册过程如下:
namespace Graphicbuttoncontrol1
{
void __fastcall PACKAGE Register()
{
//注册控件
TComponentClass classes[1] = {__classid(TGraphicButtonControl1)};
RegisterComponents("Samples", classes, 0);
//注册属性编辑器
RegisterPropertyEditor(
__typeinfo(TMyFile),//注意:自定义的封装类
__classid(TGraphicButtonControl1),//控件类
"UIPicturePath",//控件的属性字体,能在IDE中可视编辑
__classid(TMyPropertyEditor)//继承来的属性编辑类
);
}
}
编译控件的时候,在bpk工程的requires下添加designide.bpi