2009-07-29 36 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

相關問題