创建时约束组件父级

xai*_*aid 3 delphi components creation parent

我希望能够限制组件的创建位置.

例如,TMyChild可以是TButton,TMyParent可以是TPanel,当我将MyChild放到其他组件上时,我希望MyChild检查它是否在TMyParent/TPanel中创建.

如果是,那么就好了,如果它不是在TMyParent/TPanel中创建的,那么取消TMyChild创建并显示一条消息,上面写着:"抱歉,MyChild需要在MyParent中创建!".

谢谢!

RRU*_*RUZ 9

您必须覆盖Controls.TControl.SetParent方法.

  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;
Run Code Online (Sandbox Code Playgroud)

  • 这不是_cancel_或_prevent_的位置.也许之后调用继承? (2认同)