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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020