如何有条件地将属性保存到DFM?

时间:2013-12-13 01:04:43

标签: delphi properties components delphi-xe2 default-value

我有一对组件,其中一个组件通过设置属性“附加”到另一个组件。例如......

type
  TMain = class(TComponent)
  ...
  published
    property Default: Integer read FDefault write SetDefault;
  end;

  TSub = class(TComponent)
  ...
  published
    property Value: Integer read GetValue write SetValue;
    property Main: TMain read FMain write SetMain;
  end;

因此,在TSub的对象检查器中,用户会选择与其关联的TMain

在子组件中,我有一个带有getter和setter的属性Value。如果子组件的值设置为0,则getter将从其附加到的Default获取TMain属性...

function TSub.GetValue: Integer;
begin
  if FValue = 0 then begin
    if Assigned(FMain) then begin
      Result:= FMain.Default;
    end else begin
      Result:= 0;
    end;
  end else begin
    Result:= FValue;
  end;
end;

这使得对象检查器(以及它自己的属性)从main而不是set 0值返回默认值。

我想要做的是确保当TSub组件的属性保存到DFM时,如果它是0则不保存此属性(因此使用默认值来自主要代替)。目前,在保存DFM之后,来自main的默认值的任何值都将保存在sub的值中,这不是我想要的。

当然,属性会被标记为default 0;,例如,如果属性的值设置为0,则该属性不会保存到DFM中。但由于默认值可能会有所不同,因此我无法标记此属性的默认值(因为它需要定义默认值)。

如何将TSub组件构建为而不是将此属性保存到DFM(如果已将其设置为0,而是使用属性中的默认值)吸气剂?

1 个答案:

答案 0 :(得分:7)

property Value: Integer read GetValue write SetValue stored IsValueStored;

,其中

function TSub.IsValueStored: Boolean;
begin
  Result := (FValue <> 0) or (FMain = nil);
end;

如果我做对了。