Welcome to Atalasoft Community Sign in | Help

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:

  1. Add a DesignerSerializationVisibility attribute – this doesn’t help
  2. Add a TypeConverter attribute with typeof(ColorConverter) – this doesn’t help
  3. Add the methods ShouldSerializeForeColor/ShouldSerializeBackColor – they don’t help
  4. 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.

Published Wednesday, August 05, 2009 9:30 AM by Steve Hawley


Friday, August 07, 2009 8:03 AM by Twitted by radicalfish

# Twitted by radicalfish

Anonymous comments are disabled