Delphi组件自定义属性不保存在DFM文件中。

4

我有一个自定义组件的属性,我不希望它保存在DFM文件中。我已经重写了DefineProperties方法,不提供ReadData和WriteData过程,期望该属性不会被保存,但它仍然被保存了。

procedure TAEFDQuery.DefineProperties(Filer: TFiler);
begin
  inherited;
  // Set the ADO Compatibility custom properties to not be saved on the DFM
  Filer.DefineProperty('CommandText', nil, nil, False);
end;

不保存此属性的原因是我已将一个项目从ADO移植到FireDAC,并创建了“虚假”属性,使一些ADO代码可以不变地运行,并将其重定向到相应的FireDAC属性。
type
    TAEFDQuery = class(TFDQuery)
    private
        function GetCommandText: string;
        procedure SetCommandText(AValue: string);
    protected
        procedure DefineProperties(Filer: TFiler); override;
    published
        property CommandText: integer read GetCommandText write SetCommandText;
    end;

implementation

procedure TAEFDQuery.SetCommandText(AValue: string);
begin
  SQL.Text := AValue;
end;

function TAEFDQuery.GetCommandText: string;
begin
  Result := SQL.Text;
end;

procedure TAEFDQuery.DefineProperties(Filer: TFiler);
begin
  inherited;
  // Set the ADO Compatibility custom properties to not be saved on the DFM
  Filer.DefineProperty('CommandText', nil, nil, False);
end;

为了保持兼容性,正确的方式是如何保留这些“伪”属性,而不必让它们填充DFM文件,并产生无用的真实属性副本?

谢谢。


2
http://docwiki.embarcadero.com/RADStudio/Sydney/en/Properties_(Delphi)#Storage_Specifiers - Brian
2个回答

9
为返回 false 的属性添加存储说明符。
 property CommandTimeout: integer read GetCommandTimeout write SetCommandTimeout stored False;

参考: 属性(Delphi)-> 存储说明符


6

另一种防止属性被保存到DFM的方法是将该属性声明为public,而不是published,因为只有published属性会在DFM中进行读写。

type
  TAEFDQuery = class(TFDQuery)
  private
    function GetCommandText: string;
    procedure SetCommandText(AValue: string);
  public
    property CommandText: integer read GetCommandText write SetCommandText;
  end;

如果在设计时暴露published属性却无法保存,那么这样做就没有意义。如果您只是试图移植一些旧代码,那么您不需要为旧属性添加设计时支持。


话虽如此,为了移植旧代码的目的,可以考虑使用类帮助器而不是派生一个完整的组件,例如:

unit MyFDQueryHelper;

interface

uses
  FireDAC.Comp.Client;

type
  TAEFDQuery = class helper for TFDQuery
  private
    function GetCommandText: string;
    procedure SetCommandText(AValue: string);
  public
    property CommandText: integer read GetCommandText write SetCommandText;
  end;

implementation

procedure TAEFDQuery.SetCommandText(AValue: string);
begin
  Self.SQL.Text := AValue;
end;

function TAEFDQuery.GetCommandText: string;
begin
  Result := Self.SQL.Text;
end;

end.

现在,您只需将MyFDQueryHelper添加到一个单元的uses子句中,该单元中的任何TFDQuery对象都会自动获得新的CommandText属性。无需使用TAEFDQuery对象替换TFDQuery对象。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接