What Not to Do (WinForms Control Flavor)
I’m writing this for anyone else who might run into this problem. I looked at a bug in some inherited code that implemented a custom WinForms control. The bug was that changes made to ForeColor and BackColor in the designer would not persist/serialize.
Here is the original code:
public override Color ForeColor {
get { return subObject.ForeColor; }
set { subObject.ForeColor = value; Invalidate(); }
}
public override Color BackColor {
get { return subObject.BackColor; }
set { subObject.BackColor = value; Invalidate(); }
}
This looks innocuous enough, but even though the colors change in the designed, they don’t show in the generated code. Here is a list of things that will NOT fix this problem:
- Add a DesignerSerializationVisibility attribute – this doesn’t help
- Add a TypeConverter attribute with typeof(ColorConverter) – this doesn’t help
- Add the methods ShouldSerializeForeColor/ShouldSerializeBackColor – they don’t help
- Call the base.ForeColor/BackColor property setters and getters.
The real problem is that ForeColor and BackColor, though they are virtual, should not be overridden.
The solution is to override OnForeColorChanged and OnBackColorChanged, call the base On…Changed method, then change the subobject and call Invalidate.