Search code examples
delphidynamicfiremonkey

How to add custom properties to dynamically (programmatically) created controls in FireMonkey?


In the app that I am building I am adding controls dynamically to TFramedScrollbox control on Form.

Here is the code that I am using:

pnlNew: TFlowLayout;
pnlNew := TFlowLayout.Create(sbMain);
pnlNew.Align := TAlignLayout.Top;
pnlNew.ClipChildren := True;

pnlNew.Parent := sbMain;

And this code is working as expected.

But I want to add dynamic properties like OrgHeight, CreateOrder, PrevControl, etc. to this programmatically created control.

How to do this?

TIA


Solution

  • You can declare an "interposer class" just above your form definition, like this:

    TFlowLayout = class(FMX.Layouts.TFlowLayout) // note fully qualified name of the class we inherit from
    private
      OrgHeight: single;
      //... other properties you want to add
    end;
    
    TForm36 = class(TForm)
      sbMain: TFramedScrollBox;
      Button1: TButton;
      //...
    

    Strictly speaking, in this case, when you create the instance dynamically at runtime, you don't really need to define the "interposer class" before the form definition. You would have to, if you would have an instance of the TFlowLayout on your form already at design time.

    From now on, the TFlowLayout you instantiate on your form has those added properties, and you can write e.g.:

    pnlNew := TFlowLayout.Create(sbMain);
    pnlNew.Align := TAlignLayout.Top;
    pnlNew.ClipChildren := True;
    pnlNew.Parent := sbMain;
    pnlNew.OrgHeight := pnlNew.Height;
    pnlNew.Height := 150;