2009-07-29 40 views
1

我有一个控件,我需要限制它在设计时可以包含的子控件的类型(将新控件拖到窗体设计器上的现有控件上)。我试图通过重写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中的错误信息的控制解除后,马上:

“孩子”不是一个孩子控制这个家长。

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

回答

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); 
    } 
} 
+0

+1的CanParent,但它仍然表示, “不是孩子的控制”。能够发出消息“你不能在Y上托管X”会更有帮助 – smirkingman 2012-02-29 21:21:06

相关问题