Anthony
Anthony

Reputation: 9571

Is it common practice to extend a WinForm control using a custom component wrapper as opposed to inheritance?

I've recently been adding custom features to some of the various WinForms Controls by creating custom Component derived classes which just wrap the Control, hooking into the needed events to perform the extra functionality.

For instance, I wanted to add drag-and-drop functionality to a few different ListBox controls in my application, so I created a DragAndDropListBoxComponent which inherits from the Component class, then add this new component to the Forms I needed to add the functionality to, setting the DragAndDropListBoxComponent's ListBox property to the list box I wanted to add the functionality to.

I like this method of extending standard Control functionality because I can create more than one custom behavior type of Component for the same Control and mix them together for some interesting effects. This also favors the Composition over Inheritance principle.

It seems to have taken me awhile to come to the realization of using Component class list this. This is partly due to never seeing it used in such a way online - hence my question. Are custom Component classes commonly used in this way?

Upvotes: 2

Views: 1613

Answers (1)

Laoujin
Laoujin

Reputation: 10229

There are other options, which one you pick doesn't matter all that much as long as it achieves the desired result and you do not have the feeling your solution is working against you at every turn.

A possible alternative is using an Extender Provider. One advantage of the Extender Provider is that you seemingly add an "AllowDragAndDrop" property to each Control. (in your case the property would be added only to ListBox instances) This new property is visible at Design Time so other consumers don't have to know the implementation nor location details of the DragAndDrop functionality, they only have to set a property in the PropertyGrid.

Another possible alternative is using the Decorator pattern. This is for example used in .NET streams: You have a stream and then you add additional behavior (buffering, (un)zipping, encryption, ...) by creating a new stream that takes the old one as a constructor parameter. In your case you would wrap a ListBox in a DragAndDropListBox. Be careful though, this approach might cause your more trouble than advantages in this particular case.

Yet another possible alternative is inheriting from the controls you want to extend and add a list of "CustomBehaviors" to the controls. CustomBehaviors would implement some interface which allows you to add new behavior to the control by adding a concrete instance of the interface to the collection.

Upvotes: 6

Related Questions