Wizzard
Wizzard

Reputation: 12702

Styling components by extending their class

From this question Passing object in reference / one place to style objects

I was just thinking, what about if I created a descendant class for the item I am styling.

eg (excuse the poor code, not in ide, but you should get what I mean)

TStyledButton = class(TButton)
  public 
     constructor Create; //This overrides the main TButton
end;

constructor TStyledButton.Create;
begin
   inherited;
   self.Color := clRed;
end;

Then in my form I just have the Button1 as a TStyledButton instead.

This would remove all extra code in the form create to handle setting styles/calling function to set styles.

The only issue is, how would this go down in the design view, will I have to register this Object (component?) so it actually shows up as usual in design view.

Upvotes: 2

Views: 892

Answers (2)

jachguate
jachguate

Reputation: 17203

While you learn about Delphi packages component writers, you can use the IDE expert to create a new component automatically add it to the component palete while creating a new design time package:

Start by creating it using the IDE expert in Component/New component:

New component

New component

When prompted, select Install to new package

New package

Provide the package (file) name and description

Package name

and voila!, you have your new component in your palette:

Component installed

Try this code:

  TMyButton = class(TButton)
  public
    constructor Create(AOwner: TComponent); override;
  end;

procedure Register;

implementation
uses Graphics;

{ TMyButton }

constructor TMyButton.Create(AOwner: TComponent);
begin
  inherited;
  Font.Style := [fsBold];
  Caption := 'Click me!';
end;

You'll get this:

My Button!

Upvotes: 6

Rafael Colucci
Rafael Colucci

Reputation: 6078

Yes, you will need to register it so it shows up in design view.

It may be a good idea since you can always continue to change your component behavior. You needed to change the component style and in the future you may need another thing.

So, I would do that.

EDIT:

You can easily change all TButtons for your own type by creating an APP that will search the DFM and PAS looking for components like TButtons and change it to your own. Or you can use GExperts replace components function.

Upvotes: 1

Related Questions