如何响应 Delphi 中对象属性字段的变化

How to respond to changes in fields of object properties in Delphi

在Delphi7中,从TGraphicControl继承一个新组件,并添加一个TFont 属性,实现paint方法使用[=写入一些字符串12=] 属性。安装组件。

在设计时,当您使用 属性 对话框更改 TFont 属性 时,它会立即反映在您的组件中。但是当您更改 TFont 的个别属性时,例如 ColorSize,您的组件将不会被重新绘制,直到您将鼠标悬停在它上面。

如何正确处理对象属性字段的变化?

TFont.OnChange 事件分配事件处理程序。在处理程序中,Invalidate() 您的控件触发重绘。例如:

type
  TMyControl = class(TGraphicControl)
  private
    FMyFont: TFont;
    procedure MyFontChanged(Sender: TObject);
    procedure SetMyFont(Value: TFont);
  protected
    procedure Paint; override;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  published
    property MyFont: TFont read FMyFont write SetMyFont;
  end;

constructor TMyControl.Create(AOwner: TComponent);
begin
  inherited;
  FMyFont := TFont.Create;
  FMyFont.OnChange := MyFontChanged;
end;

destructor TMyControl.Destroy;
begin
  FMyFont.Free;
  inherited;
end;

procedure TMyControl.MyFontChanged(Sender: TObject);
begin
  Invalidate;
end;

procedure TMyControl.SetMyFont(Value: TFont);
begin
  FMyFont.Assign(Value);
end;

procedure TMyControl.Paint;
begin
  // use MyFont as needed...
end;