如何禁止在C#中将控件添加到除其父级之外的任何容器

时间:2014-03-06 05:57:45

标签: c# winforms controls

美好的一天。我有一次将我的控件添加到ParentControl.Controls。如何禁止将此控件添加到除其父级之外的任何容器中?

更新:

public class CompositeControl : Control
{
    public CompositeControl(EmbeddedControl[] embeddedControls)
    {
        this.Controls.AddRange(embeddedControls);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        foreach (Control c in this.Controls)
        {
            if (c is EmbeddedControl) c.Locaion = new Point(someX, someY);
            base.OnPaint(e);
        }
    }
}

public class EmbeddedControl : UserControl
{
}

EmbeddedControl uc1 = new EmbeddedControl(); //design by user
EmbeddedControl uc2 = new EmbeddedControl(); //design by user
EmbeddedControl[] coll = new EmbeddedControl[] {uc1, uc2};
CompositeControl compControl = new CompositeControl(coll);

Button b = new Button();
compControl.Controls.Add(b);
b.location = new Point(100, 100);
...
compControl.Controls.Remove(b); //ok

我想让它变得不可能:

Panel p = new Panel();
p.Controls.Add(uc1); //uc1 will removed from compControl.Controls

1 个答案:

答案 0 :(得分:1)

您可以制作自己的面板类,可以从Panel中进行操作。如果有人通过该方法添加控件,则会将其删除。我希望这是你想要实现的目标。