Jason Z
Jason Z

Reputation: 13422

How do you create a .NET winforms custom control that updates the designer?

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?

Upvotes: 1

Views: 1105

Answers (3)

Hans Passant
Hans Passant

Reputation: 941873

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; }
    }
}

Upvotes: 5

Ravisha
Ravisha

Reputation: 3343

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

Upvotes: 0

Gerrie Schenck
Gerrie Schenck

Reputation: 22368

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.

Upvotes: 1

Related Questions