Styling components by extending their class

杀马特。学长 韩版系。学妹 提交于 2019-12-12 19:13:42

问题


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.


回答1:


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:

When prompted, select Install to new package

Provide the package (file) name and description

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

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:




回答2:


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.



来源:https://stackoverflow.com/questions/5438589/styling-components-by-extending-their-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!