有关属性的概述,请参阅 属性概述。 定义属性时,有几个重要注意事项:
必须将特征应用于您定义的属性。 属性指定设计器应如何显示属性。 有关详细信息,请参阅组件
Design-Time 属性。 如果更改属性会影响控件的视觉显示,请从
set
访问器调用 Invalidate 方法(控件继承自 Control)。 Invalidate 又调用重新绘制控件的 OnPaint 方法。 对 Invalidate 的多次调用会生成对 OnPaint 的一次调用,以提高效率。.NET Framework 类库为常见数据类型(如整数、十进制数、布尔值等)提供类型转换器。 类型转换器的用途通常是提供字符串到值转换(从字符串数据到其他数据类型)。 常见的数据类型与默认类型转换器相关联,这些转换器将值转换为字符串,将字符串转换为适当的数据类型。 如果定义自定义(即非标准)数据类型的属性,则必须应用一个属性,该属性指定要与该属性关联的类型转换器。 你还可以使用属性将自定义UI类型编辑器与属性关联起来。 UI 类型编辑器提供用于编辑属性或数据类型的用户界面。 颜色选取器是 UI 类型编辑器的示例。 本主题末尾提供了属性示例。
说明
如果没有类型转换器或 UI 类型编辑器可供自定义属性使用,则可根据扩展设计时支持中所述来实现一个。
以下代码片段为自定义控件 FlashTrackBar
定义名为 EndColor
的自定义属性。
Public Class FlashTrackBar
Inherits Control
...
' Private data member that backs the EndColor property.
Private _endColor As Color = Color.LimeGreen
' The Category attribute tells the designer to display
' it in the Flash grouping.
' The Description attribute provides a description of
' the property.
<Category("Flash"), _
Description("The ending color of the bar.")> _
Public Property EndColor() As Color
' The public property EndColor accesses _endColor.
Get
Return _endColor
End Get
Set
_endColor = value
If Not (baseBackground Is Nothing) And showGradient Then
baseBackground.Dispose()
baseBackground = Nothing
End If
' The Invalidate method calls the OnPaint method, which redraws
' the control.
Invalidate()
End Set
End Property
...
End Class
public class FlashTrackBar : Control {
...
// Private data member that backs the EndColor property.
private Color endColor = Color.LimeGreen;
// The Category attribute tells the designer to display
// it in the Flash grouping.
// The Description attribute provides a description of
// the property.
[
Category("Flash"),
Description("The ending color of the bar.")
]
// The public property EndColor accesses endColor.
public Color EndColor {
get {
return endColor;
}
set {
endColor = value;
if (baseBackground != null && showGradient) {
baseBackground.Dispose();
baseBackground = null;
}
// The Invalidate method calls the OnPaint method, which redraws
// the control.
Invalidate();
}
}
...
}
以下代码片段将类型转换器和 UI 类型编辑器与属性 Value
相关联。 在这种情况下,Value
是一个整数,并且具有默认类型转换器,但 TypeConverterAttribute 属性应用自定义类型转换器(FlashTrackBarValueConverter
),使设计器能够将其显示为百分比。 UI 类型编辑器 FlashTrackBarValueEditor
允许直观显示百分比。 此示例还显示由 TypeConverterAttribute 或 EditorAttribute 属性指定的类型转换器或编辑器将替代默认转换器。
<Category("Flash"), _
TypeConverter(GetType(FlashTrackBarValueConverter)), _
Editor(GetType(FlashTrackBarValueEditor), _
GetType(UITypeEditor)), _
Description("The current value of the track bar. You can enter an actual value or a percentage.")> _
Public ReadOnly Property Value() As Integer
...
End Property
[
Category("Flash"),
TypeConverter(typeof(FlashTrackBarValueConverter)),
Editor(typeof(FlashTrackBarValueEditor), typeof(UITypeEditor)),
Description("The current value of the track bar. You can enter an actual value or a percentage.")
]
public int Value {
...
}