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

Viewed 25971

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 );
    }
8 Answers

I didn't have any luck using the DefaultValue attribute with properties of type Color or of type Font, but I did succeed with these methods described in the msdn documentation:

"Defining Default Values with the ShouldSerialize and Reset Methods" http://msdn.microsoft.com/en-us/library/53b8022e(v=vs.90).aspx

I used Color.Empty and null, respectively, as the values for my private backing fields and had the public properties always return something useful.

You can set specific Attribute in the component.designer.cs in the Initializecomponent Method:

  private void InitializeComponent()
    {
        components = new System.ComponentModel.Container();
        this.LineColor= System.Drawing.Color.FromArgb(255, 0, 0);
    }

Rebuild the project and everything should also show up in the

I used this code and it worked perfectly

Private _BackColorSelect As Color = Color.FromArgb(214, 234, 248)

<DefaultValue(GetType(Color), "214, 234, 248")>
Public Property BackColorSelect As Color
    Get
        Return _BackColorSelect
    End Get
    Set(value As Color)
        _BackColorSelect = value
    End Set
End Property
Related