Prevent Winforms Designer from Generating Property Values for Inherited Controls

I should emphasize that this isn’t normally the way you do this, the [DefaultValue] attribute is normally the correct choice. But you are working with a property of type Color, it is not simple to write the attribute for that in a flexible way. The arguments you can pass to an attribute constructor can be only a select few data types, Color isn’t one of them. You’d have to craft a string that ColorConverter can understand, that’s both ugly and hard to maintain.

PropertyGrid has a secondary way of providing defaults for “difficult” properties, it will also look for specially named private members in the class. Given a property named “Xxxx”, it looks for the following:

  • DefaultXxxx, a property with just a getter that returns the default value
  • ResetXxxx(), a method that can run when the user selects the Reset context menu item
  • ShouldSerializeXxxx(), a method that should return false if the value of the property should not be persisted.

Which makes this code work:

public class MyGridView : DataGridView {
    public MyGridView() {
        this.BackgroundColor = DefaultBackgroundColor;
    }
    public new Color BackgroundColor {
        get { return base.BackgroundColor; }
        set { base.BackgroundColor = value;  }
    }
    private bool ShouldSerializeBackgroundColor() {
        return !this.BackgroundColor.Equals(DefaultBackgroundColor);
    }
    private void ResetBackgroundColor() {
        this.BackgroundColor = DefaultBackgroundColor;
    }
    private static Color DefaultBackgroundColor {
        get { return Color.Red; }
    }
}

Note that the ResetBackgroundColor() method is not actually necessary since no special effects are required when the user resets the property, I just included it for completeness.

Leave a Comment