Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

When you select a component on a design surface, the entries in the Property Browser are rendered from the design-time control instance. When you edit properties in the Property Browser, the component's design-time instance is updated with the new property values. This synchronicity isn't as straightforward as it seems, however, because the Property Browser displays properties only as text, even though the source properties can be of any type. As values shuttle between the Property Browser and the design-time instance, they must be converted back and forth between the string type and the type of the property.

Enter the type converter, the translator droid of .NET, whose main goal in life is to convert between types. For string-to-type conversion, a type converter is used for each property displayed in the Property Browser, as shown in Figure 9.20.

09fig20.gifFigure 9.20. The Property Browser and Design-Time Conversion




.NET offers the TypeConverter class (from the System.ComponentModel namespace) as the base implementation type converter. .NET also gives you several derivations—including StringConverter, Int32Converter, and DateTimeConverter—that support conversion between common .NET types. If you know the type that needs conversion at compile time, you can create an appropriate converter directly:

// Type is known at compile time
TypeConverter converter = new Int32Converter();

Or, if you don't know the type that needs conversion until run time, let the TypeDescriptor class (from the System.ComponentModel namespace) make the choice for you:

// Don't know the type before run time
object myData = 0;
TypeConverter converter = TypeDescriptor.GetConverter(myData.GetType());

The TypeDescriptor class provides information about a particular type or object, including methods, properties, events, and attributes. TypeDescriptor.GetConverter evaluates a type to determine a suitable TypeConverter based on the following:

  1. Checking whether a type is adorned with an attribute that specifies a particular type converter.

  2. Comparing the type against the set of built-in type converters.

  3. Returning the TypeConverter base if no other type converters are found.

Because the Property Browser is designed to display the properties of any component, it can't know specific property types in advance. Consequently, it relies on TypeDescriptor.GetConverter to dynamically select the most appropriate type converter for each property.

After a type converter is chosen, the Property Browser and the design-time instance can perform the required conversions, using the same fundamental steps as those shown in the following code:

// Create the appropriate type converter
object myData = 0;
TypeConverter converter = TypeDescriptor.GetConverter(myData.GetType());
   
   // Can converter convert int to string?
   if( converter.CanConvertTo(typeof(string)) ) {
   // Convert it
   object intToString = converter.ConvertTo(42, typeof(string));
   }
   
   // Can converter convert string to int?
   if( converter.CanConvertFrom(typeof(string)) ) {
   // Convert it
   object stringToInt = converter.ConvertFrom("42");
   }
   

When the Property Browser renders itself, it uses the type converter to convert each design-time instance property to a string representation using the following steps:

  1. CanConvertTo: Can you convert from the design-time property type to a string?

  2. ConvertTo: If so, please convert property value to string.

The string representation of the source value is then displayed at the property's entry in the Property Browser. If the property is edited and the value is changed, the Property Browser uses the next steps to convert the string back to the source property value:

  1. CanConvertFrom: Can you convert back to the design-time property type?

  2. ConvertFrom: If so, please convert string to property value.

Some intrinsic type converters can do more than just convert between simple types. To demonstrate, let's expose a Face property of type ClockFace, allowing developers to decide how the clock is displayed, including options for Analog, Digital, or Both:

public enum ClockFace {
  Analog = 0,
  Digital = 1,
  Both = 2
}

class ClockControl : Control {
  ClockFace face = ClockFace.Both;
  public ClockFace Face {
    get { ... }
    set { ... }
  }
  ...
}

TypeDescriptor.GetConverter returns an EnumConverter, which contains the smarts to examine the source enumeration and convert it to a drop-down list of descriptive string values, as shown in Figure 9.21.

09fig21.gifFigure 9.21. Enumeration Type Displayed in the Property Browser via EnumConverter




Custom Type Converters

Although the built-in type converters are useful, they aren't enough if your component or control exposes properties based on custom types, such as the clock control's HourHand, MinuteHand, and SecondHand properties, shown here:

public class Hand {
  public Hand(Color color, int width) {
    this.color = color;
    this.width = width;
  }
  public Color Color {
    get { return color; }
    set { color = value; }
  }
  public int Width {
    get { return width; }
    set { width = value; }
  }
  Color  color = Color.Black;
  int    width = 1;
}

public class ClockControl : Control {
  public Hand HourHand { ... }
   public Hand MinuteHand { ... }
   public Hand SecondHand { ... }
   }
   

The idea is to give developers the option to pretty up the clock's hands with color and width values. Without a custom type converter,5 the unfortunate result is shown in Figure 9.22.

09fig22.gifFigure 9.22. Complex Properties in the Property Browser




Just as the Property Browser can't know which types it will be displaying, .NET can't know which custom types you'll be developing. Consequently, there aren't any type of converters capable of handling them. However, you can hook into the type converter infrastructure to provide your own. Building a custom type converter starts by deriving from the TypeConverter base class:

public class HandConverter : TypeConverter { ... }
   

To support conversion, HandConverter must override CanConvertFrom, ConvertTo, and ConvertFrom:

public class HandConverter : TypeConverter {
  public override bool
   CanConvertFrom(
   ITypeDescriptorContext context, Type sourceType) {...}
   
   public override object
   ConvertFrom(
   ITypeDescriptorContext context,
   CultureInfo info,
   object value) {...}
   
   public override object
   ConvertTo(
   ITypeDescriptorContext context,
   CultureInfo culture,
   object value,
   Type destinationType) {...}
   }
   

CanConvertFrom lets clients know what it can convert from. In this case, HandConverter reports that it can convert from a string type to a Hand type:

public override bool CanConvertFrom(
  ITypeDescriptorContext context, Type sourceType) {

  // We can convert from a string to a Hand type
  if( sourceType == typeof(string) ) { return true; }
  return base.CanConvertFrom(context, sourceType);
}

Whether the string type is in the correct format is left up to ConvertFrom, which actually performs the conversion. HandConverter expects a multivalued string. It splits this string into its atomic values and then uses it to instantiate a Hand object:

public override object ConvertFrom(
  ITypeDescriptorContext context, CultureInfo info, object value) {

    // If converting from a string
    if( value is string ) {
      // Build a Hand type
      try {
        // Get Hand properties
        string propertyList = (string)value;
        string[] properties = propertyList.Split(';');
        return new Hand(Color.FromName(properties[0].Trim()),
                        int.Parse(properties[1]));
      }
      catch {}
      throw new ArgumentException("The arguments were not valid.");
    }
    return base.ConvertFrom(context, info, value);
  }
  ...
}

ConvertTo converts from a Hand type back to a string:

public override object ConvertTo(
  ITypeDescriptorContext context,
  CultureInfo culture,
  object value,
  Type destinationType) {

  // If source value is a Hand type
  if( value is Hand ) {
    // Convert to string
    if( (destinationType == typeof(string)) ) {
      Hand hand = (Hand)value;
      string color = (hand.Color.IsNamedColor ?
                      hand.Color.Name :
                      hand.Color.R + ", " +
                        hand.Color.G + ", " +
                        hand.Color.B);
      return string.Format("{0}; {1}", color, hand.Width.ToString());
    }
  }
  return base.ConvertTo(context, culture, value, destinationType);
}

You may have noticed that HandConverter doesn't implement a CanConvertTo override. The base implementation of TypeConverter.CanConvertTo returns a Boolean value of true when queried for its ability to convert to a string type. Because this is the right behavior for HandConverter (and for most other custom type converters), there's no need to override it.

When the Property Browser looks for a custom type converter, it looks at each property for a TypeConverterAttribute:

public class ClockControl : Control {
  ...
  [ TypeConverterAttribute (typeof(HandConverter)) ]
   public Hand HourHand { ... }
   
   [TypeConverterAttribute (typeof(HandConverter)) ]
   public Hand MinuteHand { ... }
   
   [TypeConverterAttribute (typeof(HandConverter)) ]
   public Hand SecondHand { ... }
   ...
   }
   

However, this is somewhat cumbersome, so it's simpler to decorate the type itself with TypeConverterAttribute:

[ TypeConverterAttribute(typeof(HandConverter)) ]
   public class Hand { ... }
   public class ClockControl : Control {
   ...
   public Hand HourHand { ... }
   public Hand MinuteHand { ... }
   public Hand SecondHand { ... }
   ...
   }
   

Figure 9.23 shows the effect of the custom HandConverter type converter.

plate23.jpgFigure 9.23. HandConverter in Action




Expandable Object Converter

Although using the UI shown in Figure 9.23 is better than not being able to edit the property at all, there are still ways it can be improved. For instance, put yourself in a developer's shoes. Although it might be obvious what the first part of the property is, it's disappointing not to be able to pick the color from one of those pretty drop-down color pickers. And what is the second part of the property meant to be? Length, width, degrees, something else?

As an example of what you'd like to see, the Font type supports browsing and editing of its subproperties, as shown in Figure 9.24.

09fig24.gifFigure 9.24. Expanded Property Value




This ability to expand a property of a custom type makes it a lot easier to understand what the property represents and what sort of values you need to provide. To allow subproperty editing, you simply change the base type from TypeConverter to ExpandableObjectConverter (from the System.ComponentModel namespace):

public class HandConverter : ExpandableObjectConverter { ... }
   

This change gives you multivalue and nested property editing support, as shown in Figure 9.25.

09fig25.gifFigure 9.25. HandConverter Derived from ExpandableObjectConverter




Although you don't have to write any code to make this property expandable, you must write a little code to fix an irksome problem: a delay in property updating. In expanded mode, a change to the root property value is automatically reflected in the nested property value list. This occurs because the root property entry refers to the design-time property instance, whereas its nested property values refer to the design-time instance's properties directly, as illustrated in Figure 9.26.

09fig26.gifFigure 9.26. Relationship between Root and Nested Properties and Design-Time Property Instance




When the root property is edited, the Property Browser calls HandConverter.ConvertFrom to convert the Property Browser's string entry to a new SecondHand instance, and that results in a refresh of the Property Browser. However, changing the nested values only changes the current instance's property values, rather than creating a new instance, and that doesn't result in an immediate refresh of the root property.

TypeConverters offer a mechanism you can use to force the creation of a new instance whenever instance property values change, something you achieve by overriding GetCreateInstanceSupported and CreateInstance. The GetCreateInstanceSupported method returns a Boolean indicating whether this support is available and, if it is, calls CreateInstance to implement it:

public class HandConverter : ExpandableObjectConverter {
  public override bool
   GetCreateInstanceSupported(
   ITypeDescriptorContext context) {
   
   // Always force a new instance
   return true;
   }
   
   public override object
   CreateInstance(
   ITypeDescriptorContext context, IDictionary propertyValues) {
   
   // Use the dictionary to create a new instance
   return new Hand(
   (Color)propertyValues["Color"],
   (int)propertyValues["Width"]);
   }
   ...
   }
   

If GetCreateInstanceSupported returns true, then CreateInstance will be used to create a new instance whenever any of the subproperties of an expandable object are changed. The propertyValues argument to CreateInstance provides a set of name/value pairs for the current values of the object's subproperties, and you can use them to construct a new instance.

Custom Type Code Serialization with TypeConverters

Although the Hand type now plays nicely with the Property Browser, it doesn't yet play nicely with code serialization. In fact, at this point it's not being serialized to InitializeComponent at all. To enable serialization of properties exposing complex types, you must expose a public ShouldSerialize<PropertyName> method that returns a Boolean:

public class ClockControl : Control {
  public Hand SecondHand { ... }
  bool ShouldSerializeSecondHand() {
   // Only serialize nondefault values
   return(
   (secondHand.Color != Color.Red) || (secondHand.Width != 1) );
   }
   ...
   }
   

Internally, the Designer looks for a method named ShouldSerialize <PropertyName> to ask whether the property should be serialized. From the Designer's point of view, it doesn't matter whether your ShouldSerialize<PropertyName> is public or private, but choosing private removes it from client visibility.

To programmatically implement the Property Browser reset functionality, you use the Reset<PropertyName> method:

public Hand SecondHand { ... }

void ResetSecondHand() {
   SecondHand = new Hand(Color.Red, 1);
   }
   

Implementing ShouldSerialize lets the design-time environment know whether the property should be serialized, but you also need to write custom code to help assist in the generation of appropriate InitializeComponent code. Specifically, the Designer needs an instance descriptor, which provides the information needed to create an instance of a particular type. The code serializer gets an InstanceDescriptor object for a Hand by asking the Hand type converter:

public class HandConverter : ExpandableObjectConverter {
  public override bool

    CanConvertTo(
      ITypeDescriptorContext context, Type destinationType) {

    // We can be converted to an InstanceDescriptor
   if( destinationType == typeof(InstanceDescriptor) ) return true;
   return base.CanConvertTo(context, destinationType);
   }
   
   public override object
   ConvertTo(
   ITypeDescriptorContext context, CultureInfo culture,
   object value, Type destinationType) {
   
   if( value is Hand ) {
   // Convert to InstanceDescriptor
   if( destinationType == typeof(InstanceDescriptor) ) {
   Hand     hand = (Hand)value;
   object[] properties = new object[2];
   Type[]   types = new Type[2];
   
   // Color
   types[0] = typeof(Color);
   properties[0] = hand.Color;
   
   // Width
   types[1] = typeof(int);
   properties[1] = hand.Width;
   
   // Build constructor
   ConstructorInfo ci = typeof(Hand).GetConstructor(types);
   return new InstanceDescriptor(ci, properties);
   }
   ...
   }
   return base.ConvertTo(context, culture, value, destinationType);
   }
   ...
   }
   

To be useful, an instance descriptor requires two pieces of information. First, it needs to know what the constructor looks like. Second, it needs to know which property values should be used if the object is instantiated. The former is described by the ConstructorInfo type, and the latter is simply an array of values, which should be in constructor parameter order. After the control is rebuilt and assuming that ShouldSerialize<PropertyName> permits, all Hand type properties will be serialized using the information provided by the HandConverter-provided InstanceDescriptor:

public class ClockControlHostForm : Form {
  ...
  void InitializeComponent() {
    ...
    this.clockControl1.HourHand =
   new ClockControlLibrary.Hand(System.Drawing.Color.Black, 2);
   ...
   }
   }
   

Type converters provide all kinds of help for the Property Browser and the Designer to display, convert, and serialize properties of custom types for components that use such properties.

  • + Share This
  • 🔖 Save To Your Account