如果不是特定类型,如何删除控件?

时间:2009-07-29 18:47:23

标签: .net winforms

我有一个控件,我需要限制它在设计时可以包含的子控件的类型(将新控件拖到窗体设计器上的现有控件上)。我试图通过覆盖OnControlAdded事件来做到这一点:

Protected Overrides Sub OnControlAdded(ByVal e As System.Windows.Forms.ControlEventArgs)
    MyBase.OnControlAdded(e)

    If e.Control.GetType() IsNot GetType(ExpandablePanel) Then
        MsgBox("You can only add the ExpandablePanel control to the TaskPane.", MsgBoxStyle.Exclamation Or MsgBoxStyle.OkOnly, "TaskPane")

        Controls.Remove(e.Control)
    End If
End Sub

这似乎有效,但是在删除控件后立即从Visual Studio收到错误消息:

'child'不是该父母的子女控制。

这是什么意思?如何在不发生错误的情况下实现此目的?

1 个答案:

答案 0 :(得分:1)

通常,您希望在两个位置处理此问题:ControlCollection和自定义设计器。

在你的控制中:

[Designer(typeof(MyControlDesigner))]
class MyControl : Control
{
    protected override ControlCollection CreateControlsInstance()
    {
        return new MyControlCollection(this);
    }

    public class MyControlCollection : ControlCollection
    {
        public MyControlCollection(MyControl owner)
            : base(owner)
        {
        }

        public override void Add(Control control)
        {
            if (!(control is ExpandablePanel))
            {
                throw new ArgumentException();
            }

            base.Add(control);
        }
    }
}

在自定义设计器中:

class MyControlDesigner : ParentControlDesigner
{
    public override bool CanParent(Control control)
    {
        return (control is ExpandablePanel);
    }
}