Search code examples
delphicomponentsparentcreation

Constraint component parent on creation


I want to be able to limit where a component is created.

Like for instance, TMyChild could be a TButton, and TMyParent could be a TPanel, and when I drop MyChild onto some other component I want MyChild to check if it is being created in a TMyParent/TPanel or not.

If it is, then fine lets do it, if it is NOT created in a TMyParent/TPanel then cancel the TMyChild creation and show a message that says something like: "Sorry, MyChild needs to be created in MyParent!".

Thank you!


Solution

  • You must override the Controls.TControl.SetParent method.

      TMyChild = class(TControl)
      protected
        procedure SetParent(AParent: TWinControl); override;
      end;
    
    
    procedure TMyChild.SetParent(AParent: TWinControl);
    begin
      if (AParent <> nil) then
      begin
        if not (AParent is TMyParent) then
          raise Exception.CreateFmt('Sorry, MyChild needs to be created in MyParent!', [ClassName]);
      end;
      inherited;
    end;