Creating a custom control in Winforms - Part 5 Default Values for interesting datatypes

 Specifying interesting datatypes in the DefaultValue attribute

 

Ok so last time we got off easy with a boolean property – what about something more complex – for example a Color? How can that be specified?

 

The DefaultValueAttribute has another overload that we can use for this – it allows us to pass in a Type and a string. We just need to figure out what the string should be and we’re in business. Creating a dummy project, I throw in these few lines of code to see what it should be:

 

TypeConverter colorTypeConverter = TypeDescriptor.GetConverter(typeof(Color));

            string blackColorString = colorTypeConverter.ConvertTo(Color.Black, typeof(string)) as string;

            this.Text = blackColorString;

 

Voila! The title bar says “Black”. This is the string that should be passed into the overload for the default value attribute. 

        [DefaultValue(typeof(Color),"Black")]

        public Color PopupColor {

            get {

                return popupColor;

            }

            set {

                popupColor = value;

            }

        }

 

Not so hard, eh? Now what was all this “TypeConverter” business? A type converter is a way of “converting” information about an object into another format, e.g. a string. The most noticeable place you’d run into it is the resx file, when information about your form gets stored as strings in the XML file.  Shawn talks a lot about them here, so I wont go into details. 

 

If the type doesnt already have a type converter, you can add one (if its your class) by creating a new class that inherits from TypeConverter and using the TypeConverter attribute above the class you want to convert. Ideally, the type converter would need to support converting to and from string. If all else fails, you can revert back to the ShouldSerialize style.