属性没有被写入,只能从Delphi XE2中读取

xai*_*aid 1 delphi properties call

我创建了自己的组件,其中包含TFont以及适当的属性.

该组件在Public声明中具有以下属性

property CaptionFont: TFont read fCaptionFont write SetCaptionFont;
Run Code Online (Sandbox Code Playgroud)

程序SetCaptionFont看起来像这样

procedure TMyComponent.SetCaptionFont(value: TFont);
begin
  fCaptionFont := value;
end;
Run Code Online (Sandbox Code Playgroud)

我试图使用以下代码将字体名称和字体大小分配给我的组件:

MyComponent.CaptionFont.Name := fGlobalStandardFontName;
MyComponent.CaptionFont.Size := fGlobalStandardFontSize;
Run Code Online (Sandbox Code Playgroud)

但是,在线路上设置断点时

MyComponent.CaptionFont.Name := fGlobalStandardFontName;
Run Code Online (Sandbox Code Playgroud)

然后单击"Trace Into(F7)"调试按钮,代码跳转到TFont代码并完全忽略SetCaptionFont过程.

我期待调用SetCaptionFont过程.

这里发生了什么?

Rem*_*eau 6

SetCaptionFont()在将值分配给子属性时不会调用,因为您没有为CaptionFont属性本身分配任何内容.

即使它被调用,SetCaptionFont()无论如何都没有正确实现.您正在获取源的所有权TFont并泄露您的原件TFont.您需要使用它Assign()来将源TFont值复制到现有值中TFont.

要检测子属性值更改(包括from Assign()),您需要将OnChange事件处理程序分配给fCaptionFont对象,例如:

constructor TMyComponent.Create(AOwner: TComponent);
begin
  inherited;
  fCaptionFont := TFont.Create;
  fCaptionFont.OnChange := CaptionFontChanged;
end;

procedure TMyComponent.SetCaptionFont(value: TFont);
begin
  fCaptionFont.Assign(value);
end;

procedure TMyComponent.CaptionFontChanged(Sender: TObject);
begin
  Invalidate;
end;

procedure TMyComponent.Paint;
begin
  // use fCaptionFont as needed...
end;
Run Code Online (Sandbox Code Playgroud)