Custom Control's Default Property Value
Recently a person put forth a query that he has written a custom control, overridden from an existing control, and using it in a Winform application. He was assigning some default values for some of the properties in the control's constructor. First time he added that control to the Winform, it showed the default values properly, however when we edited the custom control, recompiled and ran the Winform application again, the control instance on the form still showed the old value.
What was he doing wrong? For some of the properties of the base control like Text, this was working but for some like BackColor, this wasn't.
Looking at the typical Winform code, you will see that in the Form's .cs code, a call being made to InitializeComponent in the constructor. If you are working with .net fwk 2.0, the implementation of this function will be in the form's designer.cs file. A quick analysis of this method reveals the reason for the above stated problem.
All the controls being used on the forms are first instantiated and then further in code, each control's properties and their assigned values are listed. For example
this.MyCustomControl1 = new MyCustomControl();
this.MyControlControl1.BackColor = System.Drawing.Color.Blue;
This means that when the form is loaded, it will first call the control's constructor and then assign the value of the BackColor property to a value of Blue. This code was generated since this control had a property BackColor and it was being initialized to Blue in the constructor. So if we can get this assignement to a value of Blue removed from the form's InitializeComponent method, when we change the value in the control's constructor, and rebuild it, it should work fine.
This is handled by using an attribute with the property. The property that you don't want to get persisted to the designer, should be tagged with the following attribute
There are other options for the DesignerSerializationVisibility enum. You can check the documentation for details on the values. Marking this as hidden, ensures that when the control is added to a form, the particular property value isn't serialized in the InitializeComponent method. Now you can go ahead and easily make changes to the property values in the control's constructor and everytime you run the application, the value being assigned in the constructor is what will get used.
Hope this helps. If you have questions, drop me a mail