Custom Controls and Design-Time Support: Part 2/2 - The DirectoryTree
(Page 2 of 7 )
In the first article in this series, we considered a DirectoryTree control that automatically displays a hierarchical list of directories in the drive indicated by the Drive property.
This control introduces several advantages over performing the same sort of work manually:
- Though the DirectoryTree is based on a TreeView control, it isolates the client programmer from TreeView-specific details like nodes. It even raises a higher lever DirectorySelected event.
- Directory entries are added automatically as needed when nodes are expanded, ensuring that the control performs equal well for small drives as for drives that have tens of thousands of subdirectories.
- All the details are completely encapsulated. All the client programmer needs to worry about is setting the Drive property and handling the DirectorySelected event.
Of course, this control had its own quirks as well.
Notably, if you set the Drive property at design time, you ended up with two copies of the root directory at run time-one created dynamically by the control, and one from the nodes that Visual Studio .NET has automatically serialized.
Last article, we demonstrated a simple workaround, but a more elegant solution is possible with a custom control designers.
Before continuing any further, we need to import three additional namespaces, the bottom three shown below. These give us access to key pieces of .NET design-time support.
using System;
using System.IO;
using System.Windows.Forms;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms.Design;
using System.Drawing.Design; Control Designers One problem with traditional ActiveX control development is that the control's design-time behavior must be coded alongside the control's runtime behavior.
In the world of .NET, this problem is neatly sidestepped by a new feature: control designers. Control designers are exclusively concerned with providing the design-time behavior for a control.
The .NET framework provides a basic control designer with the ControlDesigner class in the System.Windows.Forms.Design namespace. It also provides derived classes that add support for child control containment and scrolling.
Controls can use the default designer (as we've done so far with the DirectoryTree control), or they can derive their own custom designers.
So why would you create your own designer?
- To add special designer tools, like context menu options.
- To remove inappropriate events or properties from view (or add design-time only events or properties).
- To add support for controls that contain other controls (like the toolbar) or controls with special needs (like menus).
Next: Filtering Control Class Members >>
More C# Articles
More By Wrox Team