views:

214

answers:

3

I have created a custom user control like this (simple example):

public class MyButton : Button
{
    public MyButton()
    {
        BackColor = Color.Blue;
    }
}

After compiling, it shows up in the form designer toolbox, and is displayed with the updated property. But, if I change the color, the controls that I am already using on the form keep their original color.

Is there a way to design a control that will propogate its changes to the designer?

A: 

I don't know if that is possible, but I do know that when you drag a control on the designer, its constructor is executed. That's why your button will be blue at first, and will not change color afterwards.

Gerrie Schenck
A: 

You are setting default value in the constructor for BackColor property,when you launch the designer it actually sets default values from constructor.

Ravisha
+3  A: 

The problem is that buttons you dropped on the form before you edited the class are already being initialized by the form's InitializeComponent() call with a different color. In other words, they override the default color you set in the constructor. What you have to do is declare the default value of the property so that the designer doesn't generate an assignment. That should look like this:

using System;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;

class MyButton : Button {
    public MyButton() {
        BackColor = Color.Blue;
    }
    [DefaultValue(typeof(Color), "Blue")]
    public override Color BackColor {
        get { return base.BackColor; }
        set { base.BackColor = value; }
    }
}
Hans Passant
Technically this works, for a single control on the form. When I drop a second control on to the form and then change the color, then the original color persists. Any ideas?
Jason Z
Look in the Designer.cs file and make sure the BackColor property isn't being assigned. Just delete the assignments if these buttons were added before you changed the code.
Hans Passant