当检测到将子控件添加到自定义控件时,请将处理程序添加到其parentchanged事件(您还希望将其添加到控件中的某种列表中,这样就可以避免添加多个处理程序以确保安全)。然后,如果父控件再次更改,请检查触发该事件的控件的父属性(如果父链位于自定义控件中的容器中,请循环父链)-如果您没有找到自己,则抛出一条狙击错误消息,如“我是一个嫉妒的控件,不希望将我的子控件移出我的监视范围”。
在你的用户控件中(请原谅半psuedocode,我是在文件复制期间完成这个完整的答案:-)
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