C# 如何防止启用设计模式的子控件移到其包含控件之外?

C# 如何防止启用设计模式的子控件移到其包含控件之外?,c#,.net,vb.net,winforms,C#,.net,Vb.net,Winforms,我有一个UserControl,其中包含我希望能够在设计时重新排列或调整大小的其他控件。因此,我有一个自定义的UserControl设计器,它继承自System.Windows.Forms.Design.ParentControlDesigner,我在设计器中对子控件调用EnableDesignMode。这样,在设计时,我可以拖放子控件来移动它们或调整它们的大小。但我也可以将子控件拖放到表单上原始UserControl之外的其他位置。是否有一种方法可以限制子控件在UserControl之外移动或

我有一个UserControl,其中包含我希望能够在设计时重新排列或调整大小的其他控件。因此,我有一个自定义的UserControl设计器,它继承自
System.Windows.Forms.Design.ParentControlDesigner
,我在设计器中对子控件调用
EnableDesignMode
。这样,在设计时,我可以拖放子控件来移动它们或调整它们的大小。但我也可以将子控件拖放到表单上原始UserControl之外的其他位置。是否有一种方法可以限制子控件在UserControl之外移动或调整大小?

当您检测到一个子控件被添加到自定义控件时,请向其parentchanged事件添加一个处理程序(您还希望将其添加到控件中的某种列表中,以避免为了安全而添加多个处理程序)。然后,如果父控件再次更改,请检查触发事件的控件的父属性(并循环父链,以防它位于自定义控件中的容器中)-如果您没有找到自己,请抛出一条snide错误消息,如“我是一个嫉妒的控件,不希望我的孩子被移出我的监管范围”

在您的用户控制中(请原谅半伪代码,我在文件复制期间完成了整个答案:-)

这是一个未经验证的想法,当然,我不知道你想做什么;希望它能起作用

dim ControlsProcessed as List (of Control)

sub OnControlAdded(sender as obj...) handles MyBase.ControlAdded
    if not in design mode, exit sub
    dim ctl as control = ctype(sender,control)
    if ControlsProcessed.Contains(ctl) then exit sub 
    ControlsProcessed.Add(ctl)
    addhandler ctl.ControlAdded,addressof (OnControlAdded) ' So you can monitor containers within yourself
    addhandler ctl.ParentChanged, addressof(OnParentChanged)
end sub

sub OnParentChanged(sender as object, e as ....)
    dim ctl as control = ctype(sender,control)
    dim pctl as control = ctl.parent
    while pctl isnot nothing
        if pctl is me then exit sub 
        [ if you want to allow moving to others of your kind: if typeof pctl is (mytype) then exit sub]
    wend
    Throw now applicationexception ("You sneaky devil you can't do that!")
End Sub