Saturday, February 7, 2009

UserControl Container at Design Time

Today I learned how to create a UserControl in C#.NET that can act as a container control at design time. In other words, the control will act like a group control; otherwise, when a control is dropped onto it, it will pass to the container control that is behind the control.

Create a UserControl.
Add a reference to System.Design; this will add the System.Windows.Forms.Design.ParentControlDesigner designer to the application. Use this to adorn the class definition of the user control.

[Designer(typeof(System.Windows.Forms.Design.ParentControlDesigner))]
public partial class ControlMovable : UserControl

Now, the user control will act as a container at design time: when controls are dropped onto the user control, they will be added to the ControlCollection class in the user control.

In order to handle events in the user control class for the controls that are added to it at runtime, handle the ControlAdded event and ControlRemoved event. Register and remove control events in these handlers.

For example, the mouse down events are sent to the controls directly. In order for the user control to handle the MouseDown event, register a MouseDown handler with the e.Control member from the event args sent to the event.

private void ControlMovable_ControlAdded(object sender, ControlEventArgs e)
{
  e.Control.MouseDown += this.ControlMovable_MouseDown;
}

private void ControlMovable_ControlRemoved(object sender, ControlEventArgs e)
{
   e.Control.MouseDown -= this.ControlMovable_MouseDown;
}


No comments:

Post a Comment

Followers