组件的设计时特性)

如果您对应用特性向公共语言运行时提供元数据不熟悉,请参见利用特性扩展元数据。因为组件可以显示在设计器(例如 Visual Studio)中,所以它们需要向设计时工具提供元数据的特性。本节说明并提供一组常用的设计时特性。

特性和设计器支持

因为设计时特性向可视设计工具提供有价值的信息,所以它们对在设计时正确显示您的控件及其成员非常重要。

在下面的代码片段中,CategoryAttribute 特性启用属性浏览器以在“Alignment”类别中显示 TextAlignment 属性。DescriptionAttribute 特性允许属性浏览器在用户单击某个属性时显示该属性的简要说明。

[
Category("Alignment"),
Description("Specifies the alignment of text.")
]
public ContentAlignment TextAlignment { //... }
<Category("Alignment"), _
Description("Specifies the alignment of text.")> _
Public Property _
TextAlignment As ContentAlignment
   ' ...
End Property
说明说明

在 Visual C# 和 Visual Basic 中,名为 特性名Attribute 的特性类在特性语法中可简单地作为 特性名 引用。

某些设计时特性是在类级别应用的。DesignerAttribute 特性在类级别应用,它通知窗体设计器使用哪个设计器类来显示控件。组件与默认的设计器 (System.ComponentModel.Design.ComponentDesigner) 关联,Windows 窗体和 ASP.NET 服务器控件与它们自己的默认设计器关联。只有在您为组件或控件定义自定义设计器时才应用 DesignerAttribute

// Associates the designer class SimpleControl.Design.SimpleDesigner
// with Simple.
[ Designer(typeof(SimpleControl.Design.SimpleDesigner))]
    public class Simple : WebControl { //... }
' Associates the designer class SimpleControl.Design.SimpleDesigner
' with Simple.
<Designer(GetType(SimpleControl.Design.SimpleDesigner))> _
Public Class Simple
    Inherits WebControl
    ' ...
End Class

属性和事件的公共特性

下表列出了常用于属性和事件的特性。

特性

应用于

说明

BrowsableAttribute

属性和事件

指定属性或事件是否应该显示在属性浏览器中。

CategoryAttribute

属性和事件

指定类别的名称,在该类别中将对属性或事件进行分组。当使用了类别时,组件属性和事件可以按逻辑分组显示在属性浏览器中。

DescriptionAttribute

属性和事件

定义一小块文本,该文本将在用户选择属性或事件时显示在属性浏览器底部。

BindableAttribute

属性

指定是否绑定到该属性。

DefaultPropertyAttribute

属性

(将此特性插入类声明前。)

指定组件的默认属性。当用户单击控件时,将在属性浏览器中选定该属性。

DefaultValueAttribute

属性

为属性设置一个简单的默认值。

EditorAttribute

属性

指定在可视设计器中编辑(更改)属性时要使用的编辑器。

LocalizableAttribute

属性

指定属性可本地化。当用户要本地化某个窗体时,任何具有该特性的属性都将自动永久驻留到资源文件中。

DesignerSerializationVisibilityAttribute

属性

指定显示在属性浏览器中的属性是否应该(以及如何)永久驻留在代码中。

TypeConverterAttribute

属性

指定将属性的类型转换为另一个数据类型时要使用的类型转换器。

DefaultEventAttribute

事件

(将此特性插入类声明前。)

指定组件的默认事件。这是当用户单击组件时在属性浏览器中选定的事件。

除非另外说明,属性和事件的特性在代码中紧接在属性或事件声明的前面。如下面的示例所示。

// To apply CategoryAttribute to the BorderColor 
// property, place it immediately before the declaration
// of the BorderColor property.
[Category("Appearance")] 
public Color BorderColor;

// To apply DescriptionAttribute to the Click event, 
// place it immediately before the declaration
// of the Click event.
[Description("The Click event of the button")]
public event EventHandler Click;
' To apply CategoryAttribute  to the BorderColor 
' property, place it before the property declaration.
<Category("Appearance")> Public BorderColor As Color

' To apply DescriptionAttribute to the Click event, 
' place it before the event declaration.
<Description("The Click event of the button")> Public Event Click

有关将设计器同组件和控件关联起来的设计时特性的信息,请参见扩展设计时支持

除了使用 .NET Framework 类库中定义的特性类之外,您还可以定义您自己的特性类。有关详细信息,请参考您的编程语言的文档或参阅编写自定义特性

请参见

任务

如何:应用 Windows 窗体控件中的特性

概念

特性与设计时支持

Windows 窗体控件中的特性

其他资源

扩展设计时支持