【问题标题】:How do I remove a control if not a specific type?如果不是特定类型,如何删除控件?
【发布时间】:2009-07-29 18:47:23
【问题描述】:

我有一个控件,我需要在设计时限制它可以包含的子控件的类型(将新控件拖到表单设计器上的现有控件上)。我试图通过覆盖 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' 不是这个父级的子控件。

这是什么意思?我怎样才能做到这一点而不发生错误?

【问题讨论】:

    标签: .net winforms


    【解决方案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);
        }
    }
    

    【讨论】:

    • CanParent +1,但它仍然说“不是子控件”。能够发出消息“您不能在 Y 上托管 X”会更有帮助
    猜你喜欢
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    相关资源
    最近更新 更多