【问题标题】:How to prevent design mode enabled child control from being moved outside of its containing control?如何防止启用设计模式的子控件移出其包含控件?
【发布时间】:2010-06-30 13:28:14
【问题描述】:
我有一个 UserControl,其中包含我希望能够在设计时重新排列或调整大小的其他控件。因此,我有一个继承自 System.Windows.Forms.Design.ParentControlDesigner 的 UserControl 的自定义设计器,并且我从设计器内部对子控件调用 EnableDesignMode。这样,在设计时,我可以拖放子控件来移动它们,或者调整它们的大小。但我也可以将子控件拖放到原始 UserControl 之外的表单上的其他位置。有没有办法可以限制子控件在 UserControl 之外移动或调整大小?
【问题讨论】:
标签:
c#
.net
vb.net
winforms
【解决方案1】:
当您检测到一个子控件被添加到您的自定义控件时,将一个处理程序添加到它的 parentchanged 事件(您还希望在您的控件中添加某种列表,这样您就可以避免添加多个处理程序以确保安全) .然后如果父级再次更改,请检查触发事件的控件的父属性(并循环父链,以防它位于自定义控件中的容器中) - 如果您没有找到自己,则抛出一个恶作剧错误像“我是一个嫉妒的控制者,不喜欢我的孩子被移出我的监督”之类的消息。
在您的用户控件中(请原谅半伪代码,我在文件复制期间完成了整个答案:-)
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
当然,这是一个未经检验的想法,我不知道你想做什么;希望它有效!