Setting a default value for a color property#

Here's a tip on how to set the default value of a color property in the Visual Studio designer.

If you have a component that has a BackColor property, for example, and you want to indicate to the Property Grid that its default color is defined as the RGB values 255/255/192 (light yellow) then you might have some trouble. You can initialize a color at runtime from these RGB values by calling Color.FromArgb(255, 255, 192), but since there's no matching constant, you can't pass this into the DefaultValueAttribute constructor:

[DefaultValue(Color.FromArgb(255, 255, 192))] // Won't compile, needs a constant value
public Color BackColor { get { ... } set { ... } }

You can try using the overloaded constructor to pass in the type of the object and an initialization string that can be parsed by a TypeConverter (just as when you type it directly into the property grid), but for some reason I've yet to discover that won't work if you use the RGB values:

[DefaultValue(typeof(Color), "255; 255; 192")] // Won't work

The trick is to use the hexadecimal value of the RGB values as such:

[DefaultValue(typeof(Color), "0xFFFFC0")] // Works, 0xFF=255, 0xFF=255, 0xC0=192

Note that you can also define system or well-known colors like this:

[DefaultValue(typeof(Color), "Red")] // Works, Red=0xFF0000

Also, check out my post on specifying default values for enums.

Blog | Programming | .NET | Quirks | VS.NET
Wednesday, March 08, 2006 4:50:35 PM (Romance Standard Time, UTC+01:00)
Additionally you can enter eg.

[DefaultValue(typeof(Color),"248, 232, 192")]

instead of the hexadecimal value.

Tuesday, December 19, 2006 5:30:09 PM (Romance Standard Time, UTC+01:00)
Thanks for the info. Saved me tons of time.
Comments are closed.
All content © 2012, Jelle Druyts
On this page

Recent Photos
www.flickr.com
This is a Flickr badge showing public photos from Jelle Druyts. Make your own badge here.
Advertising
Top Picks
Statistics
Total Posts: 350
This Year: 0
This Month: 0
This Week: 0
Comments: 530
Archives
Sitemap
Disclaimer
This is my personal website, not my boss', not my mother's, and certainly not the pope's. My personal opinions may be irrelevant, inaccurate, boring or even plain wrong, I'm sorry if that makes you feel uncomfortable. But then again, you don't have to read them, I just hope you'll find something interesting here now and then. I'll certainly do my best. But if you don't like it, go read the pope's blog. I'm sure it's fascinating.

Powered by:
newtelligence dasBlog 2.0.7226.0

Sign In