[ACCEPTED]-How to set the default value of Colors in a custom control in Winforms?-winforms

Accepted answer
Score: 26

The trick is to use the Hex code of the 3 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 2 am not sure and have normally used either 1 the named colors or the hex code.

Score: 11

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

private Color lineColor = Color.Red;

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

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

Edit

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

You have to override 6 the BackColor property of the base control, add 5 a new DefaultValueAttribute for your new property, and 4 then actually set the default color in the 3 constructor or in the InitializeComponent() method 2 (in the designer.cs file), which is probably 1 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;
        }
    }
}
Score: 4

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

More info in this KB article.

Score: 0

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

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

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

Score: 0

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

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

Rebuild 2 the project and everything should also show 1 up in the

Score: 0

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

0

More Related questions