views:

122

answers:

2

How does one tell the designer the default value of a Property when it is not one of the types supported by DefaultValue()? For instance, a Padding, or a Font.

Normally, when you use a Windows Forms control, the default values will be in a normal font in the Properties window, and changed (non-default) values will be in bold. E.g.

Image of properties windows with non-default values in bold

In this sample, the default value of ShowAddress is false and the default value of ShowName is true. This effect is achieved with the following:

[DefaultValue(false)]
public bool ShowAddress {
  get { return mShowAddress; }
  set { 
    mShowAddress = value; 
    Invalidate();
  }
}

[DefaultValue(true)]
public bool ShowName { ... }

However, when I tried to do something for Padding, I failed miserably:

[DefaultValue(new Padding(2))]
public Padding LabelPadding { ... }

Which of course won't compile.

How on Earth would I do this?

+1  A: 

Try this:

private static Padding DefaultLabelPadding = new Padding(2);
private internalLabelPadding = DefaultLabelPadding;
public Padding LabelPadding { get { return internalLabelPadding; } set { internalLabelPadding = value; LayoutNow(); } }

// next comes the magic
bool ShouldSerializeLabelPadding() { return LabelPadding != DefaultLabelPadding; }

The property browser looks for a function named ShouldSerializeXYZ for each property XYZ. Whenever ShouldSerializeXYZ returns false, it doesn't write anything during code generation.

EDIT: documentation:

Ben Voigt
It doesn't seem to work for me. Using Visual C# 2008. After putting in the code it wrote the property to the form designer, after setting it back to the default, and never took away the bolding in the Properties Window.
Vincent McNabb
It also doesn't work in Visual C# 2010
Vincent McNabb
Sorry, I had the naming wrong. I also added a link to the documentation.
Ben Voigt
Perfect! Thank you very much :-)
Vincent McNabb
+1  A: 

Try this:

[DefaultValue( typeof( Padding ), "2" )]
public Padding LabelPadding
{
    get { return _labelPadding; }
    set { _labelPadding = value; }
}
Adel Hazzah
That doesn't work, but [DefaultValue(typeof(Padding), "2, 2, 2, 2")] does work.
Vincent McNabb
How about an Up Vote then, since that got you to your solution?
Adel Hazzah