Subclassing an Existing Control

Subclassing an existing control is the best approach if your needs are only slightly different from one of the standard .NET Framework controls. By inheriting from an existing control class, you are riding on top of its behavior and appearance; it’s up to you to then add the specialized code to your new control class.

For example, suppose that you want a text box that turns red anytime a numeric (that is, nonalphabetic) character is entered. This is easy to do with just a few lines of code sitting in the TextBox control’s TextChanged event, but consolidating this behavior into its own class provides a reuse factor.

You start by adding a new user control to the project. User controls actually inherit from the UserControl class; because you want to inherit from the TextBox class, you need to change the class definition by using the code editor. After you do that, you can place the new component on a form and use its functionality.

Working with an Inherited Control

Because TextBox already has a UI, you don’t need to do anything about the appearance of the control. In fact, it works just like any other text box control within the Windows Forms Designer (see Figure 20.30).

Image

FIGURE 20.30 A control derived from TextBox.

The Properties window for the control behaves as expected, and double-clicking the control immediately takes you to an open code editor window. In short, the design-time experience remains fully functional and requires no effort on the part of the developer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset