views:

134

answers:

1

I have a UserControl that contains other controls that I would like to be able to rearrange or resize at design time. So I have a custom designer for the UserControl that inherits from System.Windows.Forms.Design.ParentControlDesigner, and I call EnableDesignMode on the child controls from within the designer. That way, at design time, I can drag and drop the child controls to move them, or resize them. But I can also drag and drop the child controls somewhere else on the form that is outside of the original UserControl. Is there a way I can limit the child controls from being moved or resized outside the UserControl?

A: 

When you detect a child control being added to your custom control, add a handler to its parentchanged event (you will also wish to add it some sort of list in your control so you can avoid adding multiple handlers just to be safe). then if the parent changes again, check the parent property of the control firing the event (and loop up the parent chain in case it is in a container with in your custom control) - if you don't find yourself, throw a snide error message like "I am a jealous control who does not like my children to be moved out of my supervision".

In your usercontrol (pardon the semi-psueduocode, I'm doing this whole answer during a filecopy:-)

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

Kind of an untested idea, of course, I have no idea what you're trying to do; hope it works!

FastAl