user1592987 user1592987 - 2 months ago 19
C# Question

Custom WinForms Controls with both System.Windows.Forms and Custom base classes

I wanted to create custom controls for Windows forms that would both have my CustomControl base class (with my custom properties methods) but did not want to create the controls from scratch, so I'd like to extend the already existing ones.

I know it's not possible to extend two abstract classes, but I needed some insights in how to accomplish these things.

In this scenario, I wanted to have something like this:


public abstract class CustomControl : Control
// some custom properties and methods here...


public sealed class CustomLabel : Label, CustomControl // <- i know this isn't possible
// some custom properties and methods here...

so in a new Form, I'd add Customlabel to the form and work correctly...

Any ideas?


You can consider using these options based on requirements:

  • You can create a base UserControl containing common properties and methods. Then instead of deriving from those controls, host them in the UserControl and expose the original control as a public property.

  • Creating extender provider components by implementing IExtenderProvider you can add some properties to controls without deriving from those controls. A ToolTip or ErrorProvider or HelpProvider are examples of such components.

  • Using NativeWindow you can handle messages of a control and override its WndProc without need to deriving from that control. You can use the native window when implementing an extender component.

  • You can use Extension Methods to add some methods to existing controls without deriving from those controls.

  • You can create a class containing some properties and methods and then when creating those derived controls, define a property of type of that class. Your derived controls can use that class to have some common properties and methods. Also if you implement some changing and changed events in that class like implementing INotifyPropertyChanged, derived controls can subscribe for those events and perform some operations based on changes.