Step 2 - Implement a Property to Specify the Format

From Appmethod Topics
Jump to: navigation, search

Go Up to Creating a Styled FireMonkey Component by Extending an Existing Component


The TClockLabel component created in Step 1 needs to define the date time format when it shows the current time as a property so that component users can specify it.

To implement the Format property, add the following one line to the published section of TClockLabelclass:

property Format: String;

Also, add a definition of the constructor to the public section as follows:

constructor Create(AOwner: TComponent); override;

After Format is changed, Label needs to be updated. To take care of updating the label, introduce the UpdateLabel method as a private member.

The code should look like this:

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;

After you insert this line, press CTRL+SHIFT+C. The IDE automatically adds a setter for the Format property, and a skeleton for the constructor. The code now should look like this:

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;

According to the documentation for System.SysUtils.DateTimeToString, the typical value for date time format is 'c'. So, initialize the FFormat field with 'c'.

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

Now implement the UpdateLabel and SetFormat methods as follows:

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

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

Previous

Next

See Also