C#设计人员如何知道C#中的Padding或其他对象/结构的默认属性 [英] How does one have the C# designer know the default property for a Padding or other object/struct in C#
问题描述
当属性不是DefaultValue()
支持的类型之一时,如何告诉设计者默认值?例如,Padding
或Font
.
通常,当您使用Windows窗体控件时,默认值将在属性"窗口中以常规字体显示,而更改后的(非默认)值将以粗体显示.例如
>
在此示例中,ShowAddress
的默认值是false
,而ShowName
的默认值是true
.此效果可通过以下方法实现:
[DefaultValue(false)]
public bool ShowAddress {
get { return mShowAddress; }
set {
mShowAddress = value;
Invalidate();
}
}
[DefaultValue(true)]
public bool ShowName { ... }
但是,当我尝试为Padding
做某事时,我惨败:
[DefaultValue(new Padding(2))]
public Padding LabelPadding { ... }
当然不会编译.
在地球上我该怎么做?
尝试一下:
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; }
属性浏览器为每个属性XYZ
寻找一个名为ShouldSerializeXYZ
的函数.只要ShouldSerializeXYZ
返回false,它就不会在代码生成过程中写任何东西.
文档:
- [1]: http://msdn.microsoft.com/zh-我们/library/ms973818.aspx
- [2]: http://msdn.microsoft.com/zh- us/library/53b8022e.aspx
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.
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:
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
这篇关于C#设计人员如何知道C#中的Padding或其他对象/结构的默认属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!