【问题标题】:How to prevent controls are added into a component derived from TCustomPanel?如何防止控件被添加到从 TCustomPanel 派生的组件中?
【发布时间】:2017-04-07 05:36:36
【问题描述】:

我定义了一个派生自 TCustomPanel 的组件,但有时我不小心在其中添加了一些其他控件。

运行时:

  TMyPanel = class(TCustomPanel)
  public
    //...
  end;

设计时:

procedure Register();
begin
  RegisterCustomModule(TCustomPanel, TCustomModule);
  RegisterComponents('MyTestComponents', [
    TMyPanel
  ]);
end;

我不希望安装和使用我的组件的人意外地在其中添加其他控件。 当组件是窗体/框架的直接子时,如何防止控件被添加到组件中?

重现行为的步骤:

  1. 创建一个新表单
  2. 添加TMyPanel
  3. 在选择TMyPanel 时,添加另一个控件

新控件将添加到面板中。

【问题讨论】:

  • TPanel 是一个容器,所以这是预期的行为。在这种情况下,您希望您的小组做什么?您是说您将永远想要在设计时或运行时添加子组件?
  • @Dsm:在设计面板本身时,我希望能够在面板内放置其他控件。但是我不希望在将面板用作表单/框架中的组件时可以将其他控件放置在面板内..
  • @ExDev:这没有任何意义。面板在设计时将始终位于窗体/框架内。除非您的意思是当面板是窗体/框架的 直接 子级时要忽略控件,但您希望它在它是另一个控件的子级时接受控件。如果是这种情况,那么您可以 1) 覆盖 SetParent() 方法并根据分配的 Parent 的类型在 ControlStyle 属性中切换 csAcceptsControls 标志,或者 2) 覆盖 ValidateInsert()方法,如果当前Parent 是Form/Frame,则抛出异常。
  • @RemyLebeau:是的,我不知道正确解释这个的词,我已经更新了问题,现在应该更清楚了。无论如何,删除 csAcceptsControls 是我想要的。

标签: delphi components


【解决方案1】:

可能最简单的方法(可以被覆盖)是在其构造函数中设置 controlStyle 元素,像这样

interface

uses
  VCL.ExtCtrls,
  VCL.Controls,
  System.Classes;

type
TMyPanel = class(TCustomPanel)
  public
    constructor Create(AOwner: TComponent); override;
  end;

implementation

{ TMyPanel }

constructor TMyPanel.Create(AOwner: TComponent);
begin
  inherited;
  // ...
  ControlStyle := ControlStyle - [ csAcceptsControls ];
end;

如果您希望能够在设计时更改此行为,您还可以发布 ControlStyle 属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-09
    • 2017-05-29
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 2023-03-14
    • 2011-01-28
    • 1970-01-01
    相关资源
    最近更新 更多