Reputation: 1476
I have a custom control that in this case derives from TextBox. In the constructor of this control i set a new Font.
public class dvTextBox : TextBox
{
public dvTextBox()
{
LoadSettings();
}
private void LoadSettings()
{
this.Font = new System.Drawing.Font("Segoe UI", 8f);
}
}
I use this control all over my application and in some cases i have touched the font property through the designer.
When i then change the font in my custom control i doesn't change for those objects where the designer has been used.
Is it somehow possible to make the code in my custom class more "important" than the auto generated designer code?
Upvotes: 0
Views: 1317
Reputation: 11273
You need to override the Font property and set a new DefaultValue on it, because you set it in the constructor the designer determined that the new value does not match the default value, and serializes the new font. Then, during construction of the object it uses the serialized value which is loaded after the constructor is run, overwriting what you put in there.
This is actually kind of difficult because the DefaultValueAttribute
doesn't take a "Font" type, nor can you construct one in the attribute. Here is a short example on how to do it:
public class dvTextBox : TextBox
{
private Font _defaultFont = new Font("Segoe UI", 8f);
public override Font Font
{
get { return base.Font; }
set
{
if (value == null)
base.Font = _defaultFont;
else
base.Font = value;
}
}
public override void ResetFont() { Font = null; }
private bool ShouldSerializeFont() { return !Font.Equals(_defaultFont); }
}
The ResetFont
and ShouldSerializeFont
functions are special methods recognized by the designer serializer to reset (right click the property, select "Reset") the property, or to determine if the property should be serialized. You can create these same two functions for all your serializable/resettable properties in the same format, ie Reset[PropertyName] and ShouldSerialize[PropertyName].
If you want to hide the Reset and ShouldSerialize from the API for the control, just decorate them with the EditorBrowsable(EditorBrowsableState.Never)
attribute.
Upvotes: 2