开发者

How does one have the C# designer know the default property for a Padding or other object/struct in C#

开发者 https://www.devze.com 2023-01-09 04:13 出处:网络
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.

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 w开发者_如何学运维ill be in a normal font in the Properties window, and changed (non-default) values will be in bold. E.g.

How does one have the C# designer know the default property for a Padding or other object/struct in C#

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?


Try this:

[DefaultValue( typeof( Padding ), "2, 2, 2, 2" )]
public Padding LabelPadding
{
    get { return _labelPadding; }
    set { _labelPadding = value; }
}


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:

  • [1]: http://msdn.microsoft.com/en-us/library/ms973818.aspx
  • [2]: http://msdn.microsoft.com/en-us/library/53b8022e.aspx
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号