Any component has a bunch of properties on it. For example, the WinForms Button control has properties like BackColor, ForeColor, Text, Name, BackgroundImage and so on. When you place a Button on the Form in the VisualStudio designer and look at the generated code, you will find only a subset of the properties are persisted in code. Typically, these are the properties for which you explicitly set a value. What is the mechanism the designer uses to achieve this behavior?
First of all, the object that controls this is the CodeDomSerializer associated with the component. It decides how the component should be persisted to code. Here are some of the rules that the CodeDomSerializer associated with common controls like Button uses (well, more accurately, the serializer leaves the decision to the PropertyDescriptor associated with the property and our implementation of the latter uses these rules):
- If the property has a DesignerSerializationVisibilityAttribute attached to it, then the serializer will use it to decide whether to serialize or not (like Visible or Hidden), and how to serialize (Content).
- For a property called XXX, if the component implements a method called ShouldSerializeXXX, we make a late bound call to it to determine whether to serialize or not. For example, for BackColor, the method we look for will be called ShouldSerializeBackColor().
- If the property has a DefaultValueAttribute specified, it is compared with the current value on the component. The property is serialized only if the current value is non-default.
Further, the designer associated with the component can also play a part in making this decision by “shadowing“ properties or by implementing ShouldSerializeXXX methods.
Not happy with this mechanism? Want to serialize your component in a different way? Sure! All you need to do is write your own Serializer class that derives from CodeDomSerializer and associate it with your component using the DesignerSerializerAttribute.
By the way, Whidbey is not just about cool new controls, layout, configuration, improved visual styles support, better design time experience etc. There are a ton of improvements to the designer infrastructure too, as we mentioned briefly at the PDC:
- A new architecture that makes it much simpler to host designers
- Improvements to the localization model (I didn’t mention above how Localizable properties get serialized – that’s a topic for another time)
- A bunch of new classes that make it easier to write custom serializers
- A provider based model that makes it easier to plugin custom type descriptors.
Some of these new classes are already documented at http://longhorn.msdn.microsoft.com. Look under the System.ComponentModel.* and System.*.Design namespaces.