【Delphi】扩展现有组件创建新的 FireMonkey 组件(步骤二)

实现指定格式的属性 

步骤 1 中创建的 TClockLabel 组件需要在显示当前时间时定义日期时间格式作为属性,以便组件用户可以指定。

一、实现指定格式的属性

要实现格式属性,请在 TClockLabel class 的发布部分添加以下一行: 

property Format: String;

另外,在公共部分添加构造函数的定义如下: 

 constructor Create(AOwner: TComponent); override;

更改格式后,需要更新标签。要更新标签,请将 UpdateLabel 方法作为私有成员引入。

代码应如下所示 :

type
TClockLabel = class(TLabel)
private
  { Private declarations }
  procedure UpdateLabel;
protected
  { Protected declarations }
public
  { Public declarations }
  constructor Create(AOwner: TComponent); override;
published
  { Published declarations }
  property Format: String;
end;

插入这一行后,按 CTRL+SHIFT+C。集成开发环境会自动为格式属性添加一个设置器,并为构造函数添加一个骨架。现在的代码应该是这样的:

type
TClockLabel = class(TLabel)
private
  FFormat: String;
  procedure SetFormat(const Value: String);
public
  constructor Create(AOwner: TComponent); override;
published
  property Format: String read FFormat write SetFormat;
end;


{ TClockLabel }

constructor TClockLabel.Create(AOwner: TComponent);
begin
  inherited;
end;

procedure TClockLabel.UpdateLabel;
begin

end;

procedure TClockLabel.SetFormat(const Value: String);
begin
  FFormat := Value;
end;

根据 System.SysUtils.DateTimeToString 的文档,日期时间格式的典型值是 “c”。因此,将 FFormat 字段初始化为 “c”。

constructor TClockLabel.Create(AOwner: TComponent);
begin
  inherited;
  FFormat := 'c';
end;

现在执行 UpdateLabel 和 SetFormat 方法如下: 

procedure TClockLabel.UpdateLabel;
begin
  Text := FormatDateTime(FFormat, Now);
end;

procedure TClockLabel.SetFormat(const Value: String);
begin
  FFormat := Value;
  UpdateLabel;
end;

二、继承父组件的样式

如果您希望您的组件继承父组件的样式,请使用以下代码: 

type
TClockLabel = class(TLabel)
private
  { Private declarations }
  procedure UpdateLabel;
  function GetDefaultStyleLookupName: string; override;
protected
  { Protected declarations }
public
  { Public declarations }
  constructor Create(AOwner: TComponent); override;
published
  { Published declarations }
  property Format: String;
end;

本步骤完,下一步骤参见《【Delphi】扩展现有组件创建新的 FireMonkey 组件(步骤三)》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

海纳老吴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值