views:

430

answers:

2

I'm trying to create a custom button where the foreColor is always crimson and the backColor is always cyan. Ugly color scheme, but I'm just trying to get it so I can create large amounts of controls with a consistent color scheme without setting each control individually. Here's how I coded the button:

public partial class CustomButton : Button
{
    private static Color _defaultForeColor = Color.Crimson;
    private static Color _defaultBackColor = Color.Cyan;

    public CustomButton()
    {
        InitializeComponent();
        base.ForeColor = _defaultForeColor;
        base.BackColor = _defaultBackColor;
    }


    public AutoScaleMode AutoScaleMode { get; set; }

    [DefaultValue(typeof(Color), "Crimson")]
    override public Color ForeColor
    {
        get { return base.ForeColor; }
        set
        {
            base.ForeColor = _defaultForeColor;
        }
    }

    [DefaultValue(typeof(Color), "Cyan")]
    public override Color BackColor
    {
        get { return base.BackColor; }
        set
        {
            base.BackColor = _defaultBackColor;
        }
    }        
}

When I drop the custom button onto my form, the background is the regular button color and the text is crimson. If I run the app it's the same also. Now if I try to modify the forecolor or backcolor in the properties window they go right back to their defaults that I set (crimson, cyan) and then they also show up that way when I run my app. How do I get the controls to show up correctly in the designer and at run time?

+1  A: 

The problem exists because UseVisualStyleBackColor is automatically set to true and you can't override it. If you change it to false, you'll notice that your button will work correctly.

One option is to override OnControlAdded of the button like this:

protected override void OnControlAdded(ControlEventArgs e) { base.OnControlAdded(e); UseVisualStyleBackColor = false; }

First time in the designer, the color won't show, but when you run the application it will work correctly.

AKoran
A: 

I suggest you bind fore and back colors to, for example, application settings (Or settings class specific to your controls). Standard button and bind in designer, or use your own descendant and bind in code. In this case you will have consistent color scheme, and, more important, you can change it without recompilation.

public class CustomButton : Button
{
    public CustomButton
    {
        InitializeComponent();
        if (!DesignMode)
        {
            DataBindings.Add(new Binding("ForeColor", Settings.Default, "ButtonForeColor", true, DataSourceUpdateMode.Never));
            DataBindings.Add(new Binding("BackColor", Settings.Default, "ButtonBackColor", true, DataSourceUpdateMode.Never));
        }
    }

    // ...
arbiter