I have a question regarding User Controls created with Visual Studio 2010.
Specifically, I have created a simple User Control extending the default Label .Net control. Using the Designer, I specified the BackColor of my User Control to “White” (note that my User Control does have an area of its own not occupied by any other control). After building the project, I used my control on a form of a second project under the same solution by dragging it from the toolbox.
After the placement of the control, I modified the very same property of my User Control and turned BackColor to “Red”. I recompiled the entire solution (with project dependencies checked – user control project first and the dependent second project last). Subsequently, I created a second instance of my User Control on the form (by dragging it from the toolbox). Although this second instance appears with “Red” background as expected, the first instance persists with the “White” BackColor.
This is highly non-intuitive to me and I am wondering why? I expect ALL controls to adopt any changes made to the base class when the changes affect properties not overriden after their placement on the form. The only conclusion I managed to derive is that it has to do with VS generating the “designer.vb” code for the first instance of the control and NEVER regenerating it afterwards, even though the base user control has been altered and recompiled.
Any ideas ?
UPDATE: Thank you all for your answers! I would like to point out that setting the BackColor property was merely an example for illustrating my point. It appears to me that even if no properties at all are defined for my custom control during design time, VS generates a standard set of properties in the code behind( in addition to any explicit properties defined by the developer). Therefore, omitting the explicit specification of properties does not always tackle the problem (the default VS mechanism of setting properties in the designer.vb file). I believe the only way to address the issue once and for all, is to set property initialization code inside the control’s New or Load method; not always a practical solution when a lot of initialization needs to be performed!
This goes wrong because you haven’t told the designer what the default value for the property is. So when you drop your custom label on a form, the designer generates this kind of code in the form’s Designer.cs file:
The marked statement ruins it. When you now change the default in the control class, any control that you’ve already dropped on any form is not going to change to that default color, the designer code overrides it.
You’ll need to use the [DefaultValue] attribute to tell the designer about your default. Like this:
Now the designer will omit the assignment and any change you make inside the control will be effective. The attribute syntax is clumsy, unfortunately you need to use a string.