【问题标题】:Published properties defaults reset in Design-time在设计时重置已发布的属性默认值
【发布时间】:2021-06-21 06:27:21
【问题描述】:

我正在开发一些组件 - 自定义按钮。我安装了它,但在设计时自定义发布的属性重置为零。首先我在谈论颜色 - 它重置为clBlack(或clBtnFace 用于Color 属性)。 Caption 重置为空字符串。我的意思是当我在设计时放置组件以形成对象检查器中的所有自定义属性时都重置为零(颜色为clBlack 等等)。我可以手动更改它,但为什么不使用我在代码中设置的默认值?问题仅在设计时。当我在运行时创建组件时,它工作正常。这是代码(以Color 属性为例)。

基类

TpfCustomButton = class(TCustomControl)
...
published
...
  property Color;
...
end;

主要代码

TpfCustomColoredButton = class(TpfCustomButton)
...
public
  constructor Create(AOwner: TComponent);
...
end;

constructor TpfCustomColoredButton.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);

  Color := $00E1E1E1;//Look at this: setting Color
  ...
end;

组件代码

TpfColoredButton = class(TpfCustomColoredButton)
published
  ...
  property Action;
  property Align;
  //And some other standard properties
end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('PF Components', [TpfColoredButton]);
end;
...

此外,只是为了测试我正在尝试这样的代码:

TpfColoredButton = class(TpfCustomColoredButton)
  public
    constructor Create(AOwner: TComponent);
  ...  
  
constructor TpfColoredButton.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  Caption := 'abc';
end;

在设计时Caption 是空的,但同样,如果我在运行时创建它,我们会看到Caption=abc 正如我们所料。在运行时,我创建了这样的新对象(并且工作正常):

TForm2 = class(TForm)  
  procedure FormCreate(Sender: TObject);
private
  pf: TpfColoredButton;
end;

procedure TForm2.FormCreate(Sender: TObject);
begin
  pf := TpfColoredButton.Create(Self);
  pf.Parent := Self;
end;

【问题讨论】:

    标签: delphi properties components design-time


    【解决方案1】:

    您正在派生类构造函数中更改属性的默认值,但您没有在属性声明中指定相同的默认值来更新其 RTTI,对象检查器和 DFM 流使用该值。

    此外,您的派生构造函数中缺少override。这就是为什么在设计时创建组件时您的属性没有正确初始化的原因。您的派生构造函数甚至没有被调用。而在运行时,您是直接调用派生构造函数。

    改变这个:

    TpfCustomColoredButton = class(TpfCustomButton)
      ...
    public
      constructor Create(AOwner: TComponent);
      ...
    end;
    

    到这里:

    TpfCustomColoredButton = class(TpfCustomButton)
      ...
    published
      ...
      property Color default $00E1E1E1;
      ...
    public
      constructor Create(AOwner: TComponent); override;
      ...
    end;
    

    对默认值与其基类不同的派生类的所有其他已发布属性执行相同操作。

    【讨论】:

    • 谢谢你,雷米!将override 添加到constructor 即可获得帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 2015-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多