Custom Controls and Design-Time Support: Part 2/2 - Custom UITypeEditors
(Page 6 of 7 )
You can also develop your own custom UITypeEditor classes to allow special settings to be configured. For example, consider the TreeView control.
Its Nodes property is a collection, but it doesn't use the standard collection editor (which only allows strings to be entered). Instead, it uses its own specialized UITypeEditor.
To create a custom type editor, you must first create a class that derives from System.Drawing.Design.UITypeEditor. You can then override the four methods shown below:
| Class | Description |
| EditValue() | Invoked when the property is edited. Generally, this is where you would create a special dialog box for property editing. |
| GetEditStyle() | Specifies whether the type editor is a DropDown (provides a list of specially drawn choices), Modal (provides a dialog box for property selection), or None (no editing supported). |
| GetPaintValueSupported() | Use this to return True if you are providing a PaintValue()implementation. |
| PaintValue() | Invoked to paint a graphical thumbnail that represents the value in the property grid. |
The next example uses the EditValue() method with the DirectoryTree control. It allows editing of the Drive property by presenting the dialog box we developed earlier:
public class DriveEditor : UITypeEditor
{
public override System.Drawing.Design.UITypeEditorEditStyle
GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
{
// We will use a window for property editing.
return UITypeEditorEditStyle.Modal;
}
public override object EditValue(
System.ComponentModel.ITypeDescriptorContext context,
System.IServiceProvider provider, object value)
{
SelectDrive frm = new SelectDrive();
// Set current drive in window.
frm.DriveSelection = (char)value;
frm.ShowDialog();
// Return the new value.
return frm.DriveSelection;
}
public override bool GetPaintValueSupported(
System.ComponentModel.ITypeDescriptorContext context)
{
// No special thumbnail will be shown for the grid.
return false;
}
} The type editor is attached to the appropriate property using an attribute:
[Category("Appearance"),
Description("A letter representing the drive the DirectoryTree will use."),
Editor(typeof(DriveEditor), typeof(UITypeEditor))]
public char Drive
{
get
{
return _drive;
}
set
{
_drive = value;
{
RefreshDisplay();
}
}
} One benefit of this design is that you can reuse this UITypeEditor with any drive property, in any control. It is specific to the property data type, not the control.
An alternative approach is to use a DirectoryInfo object to represent the drive instead of an underlying char. Because the property editing is now handled by the UITypeEditor, there's no need to choose a basic type that can be edited with the default design-time support built into the property grid.
Next: Conclusion >>
More C# Articles
More By Wrox Team