编写组件如何将属性的值保存到DFM文件中?

上一篇 / 下一篇  2008-01-18 10:17:06 / 个人分类:Delphi程序设计

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 X9hoM
property 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;?@/SR C0
/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-Y
ITPUB个人空间%wrK5Z%p0S$po&i0x
如果是record(结构),数组(array),则需要自己保存,保存方法与非published属性的保存方法相同。
.X*u'v_bd9_/U2ZGF5d0
"{9f(qVm+oQ;|Z0如果是自定义的类,分两种情况
{ A@)i H#Gh0继承自TPersistent的类ITPUB个人空间;r h(WLx%|!bw
会做为子组件保存在DFM文件中,类似:MyData.Text = 'aaa',存储的限制和组件的要求一样,不同的仅仅是它作为组件的子组件保存。ITPUB个人空间$v8_&a q6s Y8n5su,l5m"p;a
继承自TComponent的类ITPUB个人空间(KYKR;{?/k6{
需要声明为子组件,使用SetSubComponent(True)进行声明,可以在创建属性对像后声明,也可以在子组件类的Create方法中。ITPUB个人空间"Vu_IC@
constructor TMyData.Create(AOwner: TComponent);
J0uh8f N8H0beginITPUB个人空间Y,C1j'e/k`-tl#N'];W
  inherited;
@:bLq5urC 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|8w
Delphi不会自动保存非published属性的值到DFM文件,为了保存这些属性,需要重写TPersistent的DefineProperties过程ITPUB个人空间S'L^koI$RRH1K
如下ITPUB个人空间#sb'K6L {
procedure DefineProperties(Filer: TFiler); override;
2t s{A7W YiD,p e Q k0ITPUB个人空间z,h1ywK jf]'[
procedure TMyStruct.DefineProperties(Filer: TFiler);ITPUB个人空间rly!N2Hg;b8VtW
begin
(B*D#m!n/k/B$N0  inherited;
M j,Q}p0  Filer.DefineProperty('Str', ReadMyStr, WriteMyStr, FStr <> '');ITPUB个人空间9Kq$b3@4T,q^8W3kZ
end;
!dm&p;SIK/J5|3X"z0使用Filer.DefineProperty过程定义需要保存的属性,它需要四个参数,第一个是参数名,并不一定要与实际在组件中使用的属性名相同,第 二个是一个Read过程,第二个是Write过程,最后一个是一个Boolean值或是返回Boolean的方法,实际使用时根据这个判断是否需要保存, 与stored的功能相同。ITPUB个人空间N6J(hT@ f
Read过程与Write过程的格式如下
P*F E4N:ni.d0  TReaderProc = procedure(Reader: TReader) of object;ITPUB个人空间 @ H1k|7Hb
TWriterProc = procedure(Writer: TWriter) of object;ITPUB个人空间bf^2OM
可以在DefineProperties中定义多个需要保存的属性。

TAG:

 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

日历

« 2008-01-26  
  12345
6789101112
13141516171819
20212223242526
2728293031  

我的存档

数据统计

  • 访问量: 41
  • 日志数: 9
  • 建立时间: 2008-01-17
  • 更新时间: 2008-01-18

RSS订阅

Open Toolbar