【问题标题】:Constraint component parent on creation创建时约束组件父级
【发布时间】:2012-03-17 15:51:35
【问题描述】:

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

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

如果是,那么就可以了,如果它不是在 TMyParent/TPanel 中创建的,则取消 创建 TMyChild 并显示类似以下内容的消息:“抱歉,需要在 MyParent 中创建 MyChild!”。

谢谢!

【问题讨论】:

    标签: delphi components parent creation


    【解决方案1】:

    您必须覆盖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;
    

    【讨论】:

    • 这不会取消阻止展示位置。也许之后调用继承?
    • 我在代码中也看不到任何取消。也许毁灭;取消会很好吗?
    • @xaid,当引发异常时,父属性未设置。所以子组件没有放在Parent组件中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    • 2015-02-17
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    相关资源
    最近更新 更多