Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the default value of Colors in a custom control in Winforms?

Tags:

I got the value to show up correctly using:

    [DefaultValue ( typeof ( Color ), "255, 0, 0" )]
    public Color LineColor
    {
        get { return lineColor; }
        set { lineColor = value; Invalidate ( ); }
    }

But after I reload the project the control is used, this value is set to White, which I can invoke Reset to get back to Red again, but I don't understand the problem.

How are you supposed to set the default value and make sure it's preserved unless I change the value manually from the default?

Actually I am also doing this, which sets Back and ForeColor to these values and the VS property editor shows them as if they are changed from the default value.

Is this wrong?

    public CoolGroupBox ( )
    {
        InitializeComponent ( );
        base.BackColor = Color.FromArgb ( 5, 5, 5 );
        base.ForeColor = Color.FromArgb ( 0, 0, 0 );
    }
like image 718
Joan Venge Avatar asked Oct 05 '09 20:10

Joan Venge


3 Answers

The trick is to use the Hex code of the color:

    [DefaultValue(typeof(Color), "0xFF0000")]
    public Color LineColor
    {
            get { return lineColor; }
            set { lineColor = value; Invalidate ( ); }
    }

I think you can also use "255, 0, 0" but am not sure and have normally used either the named colors or the hex code.

like image 54
JDunkerley Avatar answered Oct 04 '22 15:10

JDunkerley


What about just setting the private member variable to the default color you want?

private Color lineColor = Color.Red;

public Color LineColor
{
        get { return lineColor; }
        set { lineColor = value; Invalidate ( ); }
}

If you want it preserved, just take out the set accessor.

Edit

I see, you want the property list in the designer to show the default color.

You have to override the BackColor property of the base control, add a new DefaultValueAttribute for your new property, and then actually set the default color in the constructor or in the InitializeComponent() method (in the designer.cs file), which is probably better since this is for the designer.

public partial class RedBackgroundControl : UserControl
{
    public RedBackgroundControl()
    {
        InitializeComponent();
        base.BackColor = Color.Red;
    }

    [DefaultValue(typeof(Color), "Red")]
    new public Color BackColor
    {
        get
        {
            return base.BackColor;
        }
        set
        {
            base.BackColor = value;
        }
    }
}
like image 20
scottm Avatar answered Oct 04 '22 16:10

scottm


The [DefaultValue(...)] attribute is a hint to designers and code generators. It is NOT an instruction to the compiler.

More info in this KB article.

like image 45
Serge Wautier Avatar answered Oct 04 '22 17:10

Serge Wautier