DefaultValue Attribute usage with Color in C#

  • Thread starter Thread starter Stephen M
  • Start date Start date
S

Stephen M

Hi,

I hope this will be a definitive post on this subject (Hope... mmm
yes)

I had a problem of trying to set default values for Color properties
on my user control. After searching round I found that the solution
boils down to the following:

1) Set the private Color value to the desired default value during
construction.

e.g.

public class MyControl : UserControl
{
....
private Color myColorProperty = Color.DarkGray;
....

This will then show up in the design time properties for the control,
but the "Default" functionality will not work and the value will
always be shown as Bold.

2) To fix the above problem, specify the DefaulValue property as
follows

[Category("Appearance")]
[Description("The Color of my thing!.")]
[DefaultValue(typeof(Color), "DarkGray")]
public Color MyColorProperty
{
get { return myColorProperty; }
set
{
myColorProperty = value;
Invalidate();
}
}

Now the property will be non-bold when it is set to "Default" (right
click over property), and it will be Bold when it is changed. This is
normal behaviour.

An important thing to notice, and something that foxed me for some
time, is that the following format of DefaultValue will NOT work (even
though it looks pretty much the same!:

[DefaultValue(typeof(Color), "Color.DarkGray")]

I hope this all helps
Steve
 
Back
Top