.net 如果不是特定类型,如何删除控件?
我有一个控件,我需要限制它在设计时可以包含的子控件的类型(将新控件拖到窗体设计器上的现有控件上)。我试图通过覆盖OnControlAdded事件来实现这一点:.net 如果不是特定类型,如何删除控件?,.net,winforms,.net,Winforms,我有一个控件,我需要限制它在设计时可以包含的子控件的类型(将新控件拖到窗体设计器上的现有控件上)。我试图通过覆盖OnControlAdded事件来实现这一点: Protected Overrides Sub OnControlAdded(ByVal e As System.Windows.Forms.ControlEventArgs) MyBase.OnControlAdded(e) If e.Control.GetType() IsNot GetType(Expandable
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”不是此父级的子控件
这是什么意思?如何在不发生错误的情况下完成此操作?通常,您需要在两个位置处理此操作: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);
}
}
通常,您希望在两个位置处理此问题: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);
}
}
+1表示CanParent,但它仍然表示“不是子控件”。如果能够为CanParent发出消息“您不能在Y上托管X”+1,则会更有帮助,但它仍然表示“不是子控件”。如果能够发出一条消息“您不能在Y上托管X”,会更有帮助