Delphi会视需要保存组件的属性值到DFM文件中,对于published属性和非published属性将区别对待。
ITPUB个人空间 h(_0T&`7\1[_E{一、published属性
}\QQj n0 必须设置有 read 和 write 的属性才出现在属性编辑面板中,也才会保存。
ITPUB个人空间*G&[/Dl4k4pf(Z\ Delphi会根据stored来判断是否需要保存属性的值,stored默认为True,如果为False则不保存。
)Px(gU~-z0property Caption: TCaption read FCaption write FCaption; //默认为True,保存
ITPUB个人空间,CpA&^t
X9hoMproperty State: TState read FState write FState stored False; //设置stored为False,不会保存
dp3Nj7h'}-M$H8W$o0property Text: String read FText write FText stored IsTextStored; //根据IsTextStored返回的值决定是否保存
*YS(Z;?@/SRC0/HJS0A"ua8Y!A!R0Delphi会自动保存以下类型属性的值
5qP8i'j G0 简单类型 (Integer、String等)
ITPUB个人空间I%]3tS#Y8} 枚举类型 (TMyData = (DATA1, DATA2)
#P&{L {bUn,e0 简单类型或枚举类型的 SET (TMyDatas = set of TMyData)
ITPUB个人空间A2h|&xU Delphi 已经定义的类 (property Label: TLabel read FLabel write SetLabel;)
p/NhsW0 property Width: Integer read FWidth write FWidth;
ITPUB个人空间[}B;A2G%k-YITPUB个人空间%wrK5Z%p0S$po&i0x如果是record(结构),数组(array),则需要自己保存,保存方法与非published属性的保存方法相同。
.X*u'v_bd9_/U2ZGF5d0"{9f(qVm+oQ;|Z0如果是自定义的类,分两种情况
{A@)iH#Gh0继承自TPersistent的类
ITPUB个人空间;r
h(WLx%|!bw会做为子组件保存在DFM文件中,类似:MyData.Text = 'aaa',存储的限制和组件的要求一样,不同的仅仅是它作为组件的子组件保存。
ITPUB个人空间$v8_&aq6sY8n5s u,l5m"p;a继承自TComponent的类
ITPUB个人空间(KYKR;{?/k6{需要声明为子组件,使用SetSubComponent(True)进行声明,可以在创建属性对像后声明,也可以在子组件类的Create方法中。
ITPUB个人空间"Vu_ IC@constructor TMyData.Create(AOwner: TComponent);
J0uh8f N8H0begin
ITPUB个人空间Y,C1j'e/k`-t l#N'];W inherited;
@:bLq5ur C
r0 SetSubComponent(True);
$y{)A"c(](Y"y0end;
ITPUB个人空间]$Q#y A\9I
E或者是
/e1{^&Vn
QV&u0MyData := TMyData.Create(Self);
Vg1G*SA%}%B)B F
j0MyData.SetSubComponent(True);
Li#|6RS+R{0ITPUB个人空间-K8Tuq)Z:N二、非published属性
ITPUB个人空间n/P?@:H1^0|8wDelphi不会自动保存非published属性的值到DFM文件,为了保存这些属性,需要重写TPersistent的DefineProperties过程
ITPUB个人空间S'L^koI$RRH1K如下
ITPUB个人空间#sb'K6L
{procedure DefineProperties(Filer: TFiler); override;
2t s{A7WYiD,p eQ k0ITPUB个人空间z,h1ywKjf]'[procedure TMyStruct.DefineProperties(Filer: TFiler);
ITPUB个人空间r ly!N2Hg;b8VtWbegin
(B*D#m!n/k/B$N0 inherited;
M
j,Q}p0 Filer.DefineProperty('Str', ReadMyStr, WriteMyStr, FStr <> '');
ITPUB个人空间9Kq$b3@4T,q^8W3kZend;
!dm&p;SIK/J5|3X"z0使用Filer.DefineProperty过程定义需要保存的属性,它需要四个参数,第一个是参数名,并不一定要与实际在组件中使用的属性名相同,第
二个是一个Read过程,第二个是Write过程,最后一个是一个Boolean值或是返回Boolean的方法,实际使用时根据这个判断是否需要保存,
与stored的功能相同。
ITPUB个人空间N6J(hT@ fRead过程与Write过程的格式如下
P*F E4N:ni.d0 TReaderProc = procedure(Reader: TReader) of object;
ITPUB个人空间@ H1k|7HbTWriterProc = procedure(Writer: TWriter) of object;
ITPUB个人空间bf^2OM可以在DefineProperties中定义多个需要保存的属性。