Before any changes we make to the Buttons collection will be serialized to code, we need to
add a TypeConverter
class and associate it with ColourButton
. A TypeConverter
helps the serializers
know how to recreate an object that is already instantiated. I'm going to use a very simple
TypeConverter
in this example, which simply tells the serializers to use the default, parameterless
constructor.
VB.NET
Friend Class ColourButtonConverter
Inherits TypeConverter
Public Overloads Overrides Function CanConvertTo(ByVal context As _
ITypeDescriptorContext, ByVal destType As Type) As Boolean
If destType Is GetType(InstanceDescriptor) Then
Return True
End If
Return MyBase.CanConvertTo(context, destType)
End Function
Public Overloads Overrides Function ConvertTo(ByVal context As _
ITypeDescriptorContext, ByVal culture As System.Globalization.CultureInfo, _
ByVal value As Object, ByVal destType As Type) As Object
If destType Is GetType(InstanceDescriptor) Then
Dim ci As System.Reflection.ConstructorInfo = _
GetType(ColourButton).GetConstructor(System.Type.EmptyTypes)
Return New InstanceDescriptor(ci, Nothing, False)
End If
Return MyBase.ConvertTo(context, culture, value, destType)
End Function
End Class
C#
internal class ColourButtonConverter : TypeConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destType)
{
if (destType == typeof(InstanceDescriptor))
return true;
return base.CanConvertTo(context, destType);
}
public override object ConvertTo(ITypeDescriptorContext context,
System.Globalization.CultureInfo culture, object value, Type destType)
{
if (destType == typeof(InstanceDescriptor))
{
System.Reflection.ConstructorInfo ci =
typeof(ColourButton).GetConstructor(
System.Type.EmptyTypes);
return new InstanceDescriptor(ci, null, false);
}
return base.ConvertTo(context, culture, value, destType);
}
}
We also need to tell the serializers that they have to go in to our Buttons property before they
will even get that far, and we do this with the DesignerSerializationVisibilityAttribute
class. Apart
from its name being such an impressive length, all this attribute does it inform the serializers what
to do with our property. We want them to delve in to the collection, so we specify Content.
When we add buttons to the control at design time, save, close the designer and re-open it, the buttons are there again. That's all we have to do with regards to serialization, and it's a big step out of the way.
Comments