在.net开发中常常需要使用一些[]里面的特性描述,我发现对常用的几个知道大概的意思,但是却不甚清楚到底有多少个特性,都如何使用。所以今天查了下msdn,把他们一一总结下来。
这些特性(属性)在System.ComponentModel下面,凡是带有Attribute结尾的的类都是可以作为方括号里面使用的。我将它们一一摘录下来,并且写上了自己的理解。
AttributeUsageAttribute
用法:
view plaincopy to clipboardprint?
[AmbientValue(typeof(Color), "Empty")]
[Category("Appearance")]
[DefaultValue(typeof(Color), "White")]
[Description("The color used for painting alert text.")]
public Color AlertForeColor
{
get
{
if (this.alertForeColorValue == Color.Empty &&
this.Parent != null)
{
return Parent.ForeColor;
}
return this.alertForeColorValue;
}
set
{
this.alertForeColorValue = value;
}
}
[AmbientValue(typeof(Color), "Empty")]
[Category("Appearance")]
[DefaultValue(typeof(Color), "White")]
[Description("The color used for painting alert text.")]
public Color AlertForeColor
{
get
{
if (this.alertForeColorValue == Color.Empty &&
this.Parent != null)
{
return Parent.ForeColor;
}
return this.alertForeColorValue;
}
set
{
this.alertForeColorValue = value;
}
}
大概含义:
如果控件上的属性具有环境行为,则必须存在此特性。环境属性向其父级查询它们的值,例如 Control.Font 属性或 Control.BackColor 属性。
通常,可视化设器使用 AmbientValueAttribute 属性来决定为属性永久保存的值。这通常是一个使属性从另一个源获取其值的值。周围值的一个示例是 Color.Empty 作为 BackColor 属性的周围值。如果您在窗体上具有一个控件,并且该控件的 BackColor 属性被设置为与该窗体的 BackColor 属性不同的颜色,则您可以通过将该控件的 BackColor 设置为 Color.Empty 来将该控件的 BackColor 属性重置为该窗体的颜色。
AttributeUsageAttribute
view plaincopy to clipboardprint?
[Category("Data")]
[Description("Indicates the source of data for the control.")]
[RefreshProperties(RefreshProperties.Repaint)]
[AttributeProvider(typeof(IListSource))]
public object DataSource
{
get
{
return this.dataGridView1.DataSource;
}
set
{
this.dataGridView1.DataSource = value;
}
}
[Category("Data")]
[Description("Indicates the source of data for the control.")]
[RefreshProperties(RefreshProperties.Repaint)]
[AttributeProvider(typeof(IListSource))]
public object DataSource
{
get
{
return this.dataGridView1.DataSource;
}
set
{
this.dataGridView1.DataSource = value;
}
}
大概含义:在 .NET Framework 对象模型中,有些情况下会有意将属性类型化为模糊的。例如,将 DataGridView.DataSource 属性类型化为 object。之所以这样,是为了让此属性可以接受多种类型的输入。遗憾的是,这样做并未提供添加元数据以描述属性特性的通用方法。对于需要元数据的类型转换器、UI 类型编辑器和其他服务,.NET Framework 中的每个 DataSource 属性都需要具有相同的元数据。AttributeProviderAttribute 对此情况进行了补救。
此属性 (Attribute) 一旦被置于属性 (Property) 上,用于获得属性 (Property) 描述符的 MemberDescriptor.Attributes 集合的属性 (Attribute) 的规则就会有所不同。通常,属性 (Property) 描述符收集本地属性 (Attribute),然后再将其与来自属性 (Property) 类型的属性 (Attribute) 进行合并。在此情况下,将从 AttributeProviderAttribute 所返回的类型中而不是从实际属性 (Property) 类型获取属性 (Attribute)。此属性 (Attribute) 用在 DataGridView.DataSource 中,以使 DataGridView.DataSource 对象的特定类型指向 IListSource,并且相应的元数据放在 IListSource 中,以启用数据绑定。在这种情况下,可以从外部轻松地向所有数据源添加元数据。
BindableAttribute
view plaincopy to clipboardprint?
[Bindable(true)]
public int MyProperty {
get {
// Insert code here.
return 0;
}
set {
// Insert code here.
}
}
[Bindable(true)]
public int MyProperty {
get {
// Insert code here.
return 0;
}
set {
// Insert code here.
}
}
大概含义:
如果已将 BindableAttribute 设置为 true 来标记属性,则应引发该属性的属性更改通知。这意味着,如果 Yes 属性 (Property) 为 Bindable,则支持双向数据绑定。如果 Bindable 是 No,则您仍可以绑定到该属性 (Property),但它不应该显示在默认的要绑定到的属性 (Property) 集中,因为它不一定引发属性 (Property) 更改通知。
BrowsableAttribute
view plaincopy to clipboardprint?
[Browsable(true)]
public int MyProperty {
get {
// Insert code here.
return 0;
}
set {
// Insert code here.
}
}
[Browsable(true)]
public int MyProperty {
get {
// Insert code here.
return 0;
}
set {
// Insert code here.
}
}
大概含义:
可视化设计器通常在“属性”窗口中显示没有可浏览属性 (Attribute) 的成员,或使用值 true 的 BrowsableAttribute 构造函数标记的成员。这些成员可以在设计时进行修改。使用值 false 的 BrowsableAttribute 构造函数标记的成员不适合在设计时进行编辑,因此,它们不会在可视化编辑器中显示。默认为 true。
CategoryAttribute
view plaincopy to clipboardprint?
[Description("The image associated with the control"),Category("Appearance")]
public Image MyImage {
get {
// Insert code here.
return image1;
}
set {
// Insert code here.
}
}
[Description("The image associated with the control"),Category("Appearance")]
public Image MyImage {
get {
// Insert code here.
return image1;
}
set {
// Insert code here.
}
}
一个 CategoryAttribute,它指示在一个设置为 Categorized 模式的 PropertyGrid 控件中列出属性 (Property) 或事件时,将关联的属性 (Property) 或事件与���关联的类别。如果没有对属性或事件应用 CategoryAttribute,则 PropertyGrid 将属性 (Property) 或事件与“杂项”类别关联。通过在 CategoryAttribute 的构造函数中指定类别的名称,可以为任何名称创建新的类别。
Category 属性 (Property) 指示该属性 (Attribute) 所代表的类别的名称。Category 属性 (Property) 还以透明方式对类别名称进行本地化。
给继承者的说明 如果使用类别名称而不是预定义的名称,并且想要本地化类别名称,则必须重写 GetLocalizedString 方法。此外,可以重写 Category 属性 (Property) 以提供您自己的本地化逻辑。 CategoryAttribute 类定义下列通用类别:
类别
说明
Action
与可用操作相关的属性 (Property)。
Appearance
与实体的外观相关的属性 (Property)。
Behavior
与实体的行为相关的属性 (Property)。
Data
与数据和数据源管理相关的属性 (Property)。
Default
组合到默认类别中的属性 (Property)。
Design
仅在设计时可用的属性 (Property)。
DragDrop
与拖放操作相关的属性 (Property)。
Focus
与焦点相关的属性 (Property)。
Format
与格式设置相关的属性 (Property)。
Key
与键盘相关的属性 (Property)。
Layout
与布局相关的属性 (Property)。
Mouse
与鼠标相关的属性 (Property)。
WindowStyle
与顶级窗体的窗口样式相关的属性 (Property)。
DataObjectAttribute
view plaincopy to clipboardprint?
[DataObjectAttribute]
public class NorthwindData
{
public NorthwindData() {}
[DataObjectMethodAttribute(DataObjectMethodType.Select, true)]
public static IEnumerable GetAllEmployees()
{
AccessDataSource ads = new AccessDataSource();
ads.DataSourceMode = SqlDataSourceMode.DataReader;
ads.DataFile = "~//App_Data//Northwind.mdb";
ads.SelectCommand = "SELECT EmployeeID,FirstName,LastName FROM Employees";
return ads.Select(DataSourceSelectArguments.Empty);
}
// Delete the Employee by ID.
[DataObjectMethodAttribute(DataObjectMethodType.Delete, true)]
public void DeleteEmployeeByID(int employeeID)
{
throw new Exception("The value passed to the delete method is "
+ employeeID.ToString());
}
}
[DataObjectAttribute]
public class NorthwindData
{
public NorthwindData() {}
[DataObjectMethodAttribute(DataObjectMethodType.Select, true)]
public static IEnumerable GetAllEmployees()
{
AccessDataSource ads = new AccessDataSource();
ads.DataSourceMode = SqlDataSourceMode.DataReader;
ads.DataFile = "~//App_Data//Northwind.mdb";
ads.SelectCommand = "SELECT EmployeeID,FirstName,LastName FROM Employees";
return ads.Select(DataSourceSelectArguments.Empty);
}
// Delete the Employee by ID.
[DataObjectMethodAttribute(DataObjectMethodType.Delete, true)]
public void DeleteEmployeeByID(int employeeID)
{
throw new Exception("The value passed to the delete method is "
+ employeeID.ToString());
}
}
大概含义:
使用 DataObjectAttribute 属性可以将某一对象标识为适合由 ObjectDataSource 对象使用。设计时类(如 ObjectDataSourceDesigner 类)使用 DataObjectAttribute 属性表示适合绑定到 ObjectDataSource 对象的对象。
更多的见:利用属性扩展元数据。
DataObjectFieldAttribute 类
view plaincopy to clipboardprint?
public class NorthwindEmployee
{
public NorthwindEmployee() { }
private int _employeeID;
[DataObjectFieldAttribute(true, true, false)]
public int EmployeeID
{
get { return _employeeID; }
set { _employeeID = value; }
}
private string _firstName = String.Empty;
[DataObjectFieldAttribute(false, false, true)]
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
private string _lastName = String.Empty;
[DataObjectFieldAttribute(false, false, true)]
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
}
public class NorthwindEmployee
{
public NorthwindEmployee() { }
private int _employeeID;
[DataObjectFieldAttribute(true, true, false)]
public int EmployeeID
{
get { return _employeeID; }
set { _employeeID = value; }
}
private string _firstName = String.Empty;
[DataObjectFieldAttribute(false, false, true)]
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
private string _lastName = String.Empty;
[DataObjectFieldAttribute(false, false, true)]
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
}
大概含义:
使用 DataObjectFieldAttribute 属性可以提供有关基础数据架构的信息。设计时类(如 ObjectDataSourceDesigner 类)使用 DataObjectAttribute 属性 (Attribute) 根据公开的架构在设计时设置属性 (Property)。
将 DataObjectFieldAttribute 属性应用于数据项对象的成员,这些对象由通过 DataObjectAttribute 属性进行标记的对象的 Select 方法返回。在下面的示例中,NorthwindData 类使用 DataObjectAttribute 属性进行标记,并从 GetAllEmployees 方法返回一个包含 NorthwindEmployee 对象的 IEnumerable 对象。NorthwindEmployee 类中的字段使用 DataObjectFieldAttribute 属性进行标记,以指示它们表示基础数据源中的数据字段。
有关使用属性的更多信息,请参见 利用属性扩展元数据。
DataObjectMethodAttribute 类
view plaincopy to clipboardprint?
[DataObjectAttribute]
public class NorthwindData
{
public NorthwindData() {}
[DataObjectMethodAttribute(DataObjectMethodType.Select, true)]
public static IEnumerable GetAllEmployees()
{
AccessDataSource ads = new AccessDataSource();
ads.DataSourceMode = SqlDataSourceMode.DataReader;
ads.DataFile = "~//App_Data//Northwind.mdb";
ads.SelectCommand = "SELECT EmployeeID,FirstName,LastName FROM Employees";
return ads.Select(DataSourceSelectArguments.Empty);
}
// Delete the Employee by ID.
[DataObjectMethodAttribute(DataObjectMethodType.Delete, true)]
public void DeleteEmployeeByID(int employeeID)
{
throw new Exception("The value passed to the delete method is "
+ employeeID.ToString());
}
}
[DataObjectAttribute]
public class NorthwindData
{
public NorthwindData() {}
[DataObjectMethodAttribute(DataObjectMethodType.Select, true)]
public static IEnumerable GetAllEmployees()
{
AccessDataSource ads = new AccessDataSource();
ads.DataSourceMode = SqlDataSourceMode.DataReader;
ads.DataFile = "~//App_Data//Northwind.mdb";
ads.SelectCommand = "SELECT EmployeeID,FirstName,LastName FROM Employees";
return ads.Select(DataSourceSelectArguments.Empty);
}
// Delete the Employee by ID.
[DataObjectMethodAttribute(DataObjectMethodType.Delete, true)]
public void DeleteEmployeeByID(int employeeID)
{
throw new Exception("The value passed to the delete method is "
+ employeeID.ToString());
}
}
一般含义:
可以使用 DataObjectMethodAttribute 标识以 DataObjectAttribute 属性进行标记的��型上的数据操作方法,以便调用方可以通过使用反射更容易地标识这些方法。在将 DataObjectMethodAttribute 属性应用于某一方法时,该属性描述该方法所执行的操作类型并指示该方法是否是某一类型的默认数据操作方法。组件(如 ObjectDataSource 控件和 ObjectDataSourceDesigner 类)检查此属性值(如果提供的话)以帮助确定在运行时调用哪一数据方法。
DefaultBindingPropertyAttribute 类
view plaincopy to clipboardprint?
// This control demonstrates a simple logging capability.
[ComplexBindingProperties("DataSource", "DataMember")]
[DefaultBindingProperty("TitleText")]
[DefaultEvent("ThresholdExceeded")]
[DefaultProperty("Threshold")]
[HelpKeywordAttribute(typeof(UserControl))]
[ToolboxItem("System.Windows.Forms.Design.AutoSizeToolboxItem,System.Design")]
public class AttributesDemoControl : UserControl
{
// This control demonstrates a simple logging capability.
[ComplexBindingProperties("DataSource", "DataMember")]
[DefaultBindingProperty("TitleText")]
[DefaultEvent("ThresholdExceeded")]
[DefaultProperty("Threshold")]
[HelpKeywordAttribute(typeof(UserControl))]
[ToolboxItem("System.Windows.Forms.Design.AutoSizeToolboxItem,System.Design")]
public class AttributesDemoControl : UserControl
{
DefaultBindingPropertyAttribute 是在类级别指定的。它可以被继承,但不允许在同一类中存在多个属性。
有关使用属性的更多信息,请参见 利用属性扩展元数据。
DefaultEventAttribute 类
view plaincopy to clipboardprint?
[DefaultEvent("CollectionChanged")]
public class MyCollection : BaseCollection {
private CollectionChangeEventHandler onCollectionChanged;
public event CollectionChangeEventHandler CollectionChanged {
add {
onCollectionChanged += value;
}
remove {
onCollectionChanged -= value;
}
}
// Insert additional code.
}
[DefaultEvent("CollectionChanged")]
public class MyCollection : BaseCollection {
private CollectionChangeEventHandler onCollectionChanged;
public event CollectionChangeEventHandler CollectionChanged {
add {
onCollectionChanged += value;
}
remove {
onCollectionChanged -= value;
}
}
// Insert additional code.
}
大概含义:属性来获取默认事件的名称。
DefaultPropertyAttribute 类
view plaincopy to clipboardprint?
[DefaultProperty("MyProperty")]
public class MyControl : Control {
public int MyProperty {
get {
// Insert code here.
return 0;
}
set {
// Insert code here.
}
}
// Insert any additional code.
}
[DefaultProperty("MyProperty")]
public class MyControl : Control {
public int MyProperty {
get {
// Insert code here.
return 0;
}
set {
// Insert code here.
}
}
// Insert any additional code.
}
大概含义:
使用 Name 属性来获取默认属性的名称。
DefaultValueAttribute 类
view plaincopy to clipboardprint?
private bool myVal=false;
[DefaultValue(false)]
public bool MyProperty {
get {
return myVal;
}
set {
myVal=value;
}
}
private bool myVal=false;
[DefaultValue(false)]
public bool MyProperty {
get {
return myVal;
}
set {
myVal=value;
}
}
大概含义:
可以使用任何值创建 DefaultValueAttribute。成员的默认值通常是其初始值。可视化设计器可以使用默认值重置成员的值。代码生成器也可使用默认值确定是否为成员生成代码。
有关更多信息,请参见 属性 (Attribute) 概述 和 利用属性扩展元数据。
DescriptionAttribute 类
view plaincopy to clipboardprint?
[Description("The image associated with the control"),Category("Appearance")]
public Image MyImage {
get {
// Insert code here.
return image1;
}
set {
// Insert code here.
}
}
[Description("The image associated with the control"),Category("Appearance")]
public Image MyImage {
get {
// Insert code here.
return image1;
}
set {
// Insert code here.
}
}
大概含义:
可视化设计器在引用组件成员时可以显示指定的说明,如在“属性”窗口中。调��� Description 访问该属性 (Attribute) 的值。
有关更多信息,请参见 属性 (Attribute) 概述 和 利用属性扩展元数据。
DesignerAttribute 类
view plaincopy to clipboardprint?
[Designer("System.Windows.Forms.Design.DocumentDesigner, System.Windows.Forms.Design.DLL",
typeof(IRootDesigner)),
DesignerCategory("Form")]
public class MyForm : ContainerControl {
// Insert code here.
}
[Designer("System.Windows.Forms.Design.DocumentDesigner, System.Windows.Forms.Design.DLL",
typeof(IRootDesigner)),
DesignerCategory("Form")]
public class MyForm : ContainerControl {
// Insert code here.
}
大概含义:
用于设计时服务的类必须实现 IDesigner 接口。
使用 DesignerBaseTypeName 属性查找设计器的基类。使用 DesignerTypeName 属性获取与该成员关联的设计器的类型名称。
DesignerCategoryAttribute 类
view plaincopy to clipboardprint?
[Designer("System.Windows.Forms.Design.DocumentDesigner, System.Windows.Forms.Design",
typeof(IRootDesigner)),
DesignerCategory("Form")]
public class MyForm : ContainerControl {
// Insert code here.
}
[Designer("System.Windows.Forms.Design.DocumentDesigner, System.Windows.Forms.Design",
typeof(IRootDesigner)),
DesignerCategory("Form")]
public class MyForm : ContainerControl {
// Insert code here.
}
大概用法:
可视化设计器可以使用设计器类别通知开发环境将要实现的设计器类型。如果没有为某个类提供任何设计器类别,开发环境可能允许设计此类,也可能不允许。可以创建任何名称的类别。
当用此属性标记类时,它被设置为常数成员。当要在代码中检查此属性的值时,必须指定常数成员。下表中的“说明”列列出了将每个值设置为的常数成员。
DesignOnlyAttribute 类
view plaincopy to clipboardprint?
[DesignOnly(true)]
public CultureInfo GetLanguage {
get {
// Insert code here.
return myCultureInfo;
}
set {
// Insert code here.
}
}
[DesignOnly(true)]
public CultureInfo GetLanguage {
get {
// Insert code here.
return myCultureInfo;
}
set {
// Insert code here.
}
}
通过将 DesignOnlyAttribute 设置为 true 进行标记的成员只能在设计时进行设置。通常,这些属性 (Property) 只能在设计时存在,并且不对应于运行时对象上的���个实际属性 (Property)。
没有属性 (Attribute) 或通过将 DesignOnlyAttribute 设置为 false 进行标记的成员可以在运行时进行设置。默认为 false。
DesignOnlyAttribute 设置为 true 的属性的值被序列化为 .resx 文件而不是 InitializeComponent 方法。
DesignTimeVisibleAttribute 类
DesignTimeVisibleAttribute 是提供给设计器的提示。对于具有 UI 的组件,设计器将忽略此属性。它仅应用于类。
如果有接受子组件的控件,则 DesignTimeVisibleAttribute 非常有用。例如,System.Windows.Forms.TreeView 控件的节点项不应显示在组件栏中,这是因为节点项是由 System.Windows.Forms.TreeView 控件绘制的。
DisplayNameAttribute 类
view plaincopy to clipboardprint?
[Description("Demonstrates DisplayNameAttribute.")]
[DisplayName("RenamedProperty")]
public bool MisnamedProperty
{
get
{
return true;
}
}
[Description("Demonstrates DisplayNameAttribute.")]
[DisplayName("RenamedProperty")]
public bool MisnamedProperty
{
get
{
return true;
}
}
默认值为属性名或事件名。GetSortedActionItems 的默认实现使用反射搜索公共属性以及不采用任何参数的公共 void 方法。GetSortedActionItems 搜索每个属性和方法的 DisplayNameAttribute,如果找到对应的字符串,将使用该字符串,而不使用属性名或方法名。
EditorBrowsableAttribute 类
view plaincopy to clipboardprint?
int ageval;
[EditorBrowsable(EditorBrowsableState.Never)]
public int Age
{
get { return ageval; }
set
{
if (!ageval.Equals(value))
{
ageval = value;
}
}
}
int ageval;
[EditorBrowsable(EditorBrowsableState.Never)]
public int Age
{
get { return ageval; }
set
{
if (!ageval.Equals(value))
{
ageval = value;
}
}
}
您可以在可视化设计器或文本编辑器中使用该类来确定用户可见的内容。例如,Visual Studio 中的“IntelliSense”引擎使用此属性来确定是否显示方法或属性。
ExtenderProvidedPropertyAttribute 类
定由扩展程序提供程序提供的属性。无法继承此类。
ImmutableObjectAttribute 类
指定对象没有可以被编辑的子属性。无法继承此类。
InheritanceAttribute 类
指示是否已从基类继承与此属性关联的组件。无法继承此类。
InitializationEventAttribute 类
注意:此类在 .NET Framework 2.0 版中是新增的。
指定在初始化时引发的事件。无法继承此类。
InstallerTypeAttribute 类
为安装组件的类型指定安装程序。
LicenseProviderAttribute 类
view plaincopy to clipboardprint?
[LicenseProvider(typeof(LicFileLicenseProvider))]
public class MyControl : Control {
// Insert code here.
protected override void Dispose(bool disposing) {
/* All components must dispose of the licenses they grant.
* Insert code here to dispose of the license. */
}
}
[LicenseProvider(typeof(LicFileLicenseProvider))]
public class MyControl : Control {
// Insert code here.
protected override void Dispose(bool disposing) {
/* All components must dispose of the licenses they grant.
* Insert code here to dispose of the license. */
}
}
当创建要授权的某组件时,必须通过用 LicenseProviderAttribute 标记该组件来指定 LicenseProvider。
使用 LicenseProvider 属性获取 LicenseProvider 的 Type。
ListBindableAttribute 类
指定列表可被用作数据源。可视化设计器应该使用该属性来确定是否在数据绑定选择器中显示特定的列表。无法继承此类。
LookupBindingPropertiesAttribute 类
view plaincopy to clipboardprint?
[LookupBindingProperties("DataSource", "DisplayMember", "ValueMember", "LookupMember")]
public class DemoControl : Control { … }
[LookupBindingProperties("DataSource", "DisplayMember", "ValueMember", "LookupMember")]
public class DemoControl : Control { … }
LookupBindingPropertiesAttribute 用于指定基于查找的绑定所使用的属性,特别是 ListBox 和 ComboBox 控件。
LookupBindingPropertiesAttribute 是在类级别指定的。该类可以被继承,但不允许在同一类中存在多个属性
MergablePropertyAttribute 类
view plaincopy to clipboardprint?
[MergableProperty(true)]
public int MyProperty {
get {
// Insert code here.
return 0;
}
set {
// Insert code here.
}
}
[MergableProperty(true)]
public int MyProperty {
get {
// Insert code here.
return 0;
}
set {
// Insert code here.
}
}
通过将 MergablePropertyAttribute 设置为 true 进行标记的属性 (Property) 可以与“属性”窗口中属于其他对象的属性 (Property) 组合。通过将 MergablePropertyAttribute 设置为 false 进行标记的属性 (Property) 必须单独显示。默认为 true。
NotifyParentPropertyAttribute 类
指示当此属性应用到的属性的值被修改时将通知父属性。无法继承此类。
ParenthesizePropertyNameAttribute 类
指示关联属性的名称在“属性”窗口中显示时是否带有括号。无法继承此类。
PasswordPropertyTextAttribute 类
view plaincopy to clipboardprint?
// This property exists only to demonstrate the
// PasswordPropertyText attribute. When this control
// is attached to a PropertyGrid control, the returned
// string will be displayed with obscuring characters
// such as asterisks. This property has no other effect.
[Category("Security")]
[Description("Demonstrates PasswordPropertyTextAttribute.")]
[PasswordPropertyText(true)]
public string Password
{
get
{
return "This is a demo password.";
}
}
// This property exists only to demonstrate the
// PasswordPropertyText attribute. When this control
// is attached to a PropertyGrid control, the returned
// string will be displayed with obscuring characters
// such as asterisks. This property has no other effect.
[Category("Security")]
[Description("Demonstrates PasswordPropertyTextAttribute.")]
[PasswordPropertyText(true)]
public string Password
{
get
{
return "This is a demo password.";
}
}
如果将 PasswordPropertyTextAttribute 属性 (Attribute) 置于属性 (Property) 或对象之上,其属性 (Property) 窗口中的文本表示形式将显示为点或星号,以指示密码字段。
PropertyTabAttribute 类
view plaincopy to clipboardprint?
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;
using System.Windows.Forms.Design;
namespace TypeCategoryTabExample
{
// This component adds a TypeCategoryTab to the propery browser
// that is available for any components in the current design mode document.
[PropertyTabAttribute(typeof(TypeCategoryTab), PropertyTabScope.Document)]
public class TypeCategoryTabComponent : System.ComponentModel.Component
{
public TypeCategoryTabComponent()
{
}
}
// A TypeCategoryTab property tab lists properties by the
// category of the type of each property.
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
public class TypeCategoryTab : PropertyTab
{
[BrowsableAttribute(true)]
// This string contains a Base-64 encoded and serialized example property tab image.
private string img = "AAEAAAD/AQAAAAAAAAAMAgAAAFRTeXN0ZW0uRHJhd2luZywgVmVyc2lvbj0xLjAuMzMwMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWIwM2Y1ZjdmMTFkNTBhM2EFAQAAABVTeXN0ZW0uRHJhd2luZy5CaXRtYXABAAAABERhdGEHAgIAAAAJAwAAAA8DAAAA9gAAAAJCTfYAAAAAAAAANgAAACgAAAAIAAAACAAAAAEAGAAAAAAAAAAAAMQOAADEDgAAAAAAAAAAAAD///9ZgABZgADzPz/zPz/zPz9AgP//gAD/gAD/AAD/AAD/AACKyub///+AAACAAAAAAP8AAP8AAP9AgP9ZgABZgABz13hz13hz13hAgP//gAD/gACA/wCA/wCA/wAA//+AAACAAAAAAP8AAP8AAP9AgP8L";
public TypeCategoryTab()
{
}
// Returns the properties of the specified component extended with
// a CategoryAttribute reflecting the name of the type of the property.
public override System.ComponentModel.PropertyDescriptorCollection GetProperties(object component, System.Attribute[] attributes)
{
PropertyDescriptorCollection props;
if( attributes == null )
props = TypeDescriptor.GetProperties(component);
else
props = TypeDescriptor.GetProperties(component, attributes);
PropertyDescriptor[] propArray = new PropertyDescriptor[props.Count];
for(int i=0; i<props.Count; i++)
{
// Create a new PropertyDescriptor from the old one, with
// a CategoryAttribute matching the name of the type.
propArray[i] = TypeDescriptor.CreateProperty(props[i].ComponentType, props[i], new CategoryAttribute(props[i].PropertyType.Name));
}
return new PropertyDescriptorCollection( propArray );
}
public override System.ComponentModel.PropertyDescriptorCollection GetProperties(object component)
{
return this.GetProperties(component, null);
}
// Provides the name for the property tab.
public override string TabName
{
get
{
return "Properties by Type";
}
}
// Provides an image for the property tab.
public override System.Drawing.Bitmap Bitmap
{
get
{
Bitmap bmp = new Bitmap(DeserializeFromBase64Text(img));
return bmp;
}
}
// This method can be used to retrieve an Image from a block of Base64-encoded text.
private Image DeserializeFromBase64Text(string text)
{
Image img = null;
byte[] memBytes = Convert.FromBase64String(text);
IFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream(memBytes);
img = (Image)formatter.Deserialize(stream);
stream.Close();
return img;
}
}
}
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;
using System.Windows.Forms.Design;
namespace TypeCategoryTabExample
{
// This component adds a TypeCategoryTab to the propery browser
// that is available for any components in the current design mode document.
[PropertyTabAttribute(typeof(TypeCategoryTab), PropertyTabScope.Document)]
public class TypeCategoryTabComponent : System.ComponentModel.Component
{
public TypeCategoryTabComponent()
{
}
}
// A TypeCategoryTab property tab lists properties by the
// category of the type of each property.
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
public class TypeCategoryTab : PropertyTab
{
[BrowsableAttribute(true)]
// This string contains a Base-64 encoded and serialized example property tab image.
private string img = "AAEAAAD/AQAAAAAAAAAMAgAAAFRTeXN0ZW0uRHJhd2luZywgVmVyc2lvbj0xLjAuMzMwMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWIwM2Y1ZjdmMTFkNTBhM2EFAQAAABVTeXN0ZW0uRHJhd2luZy5CaXRtYXABAAAABERhdGEHAgIAAAAJAwAAAA8DAAAA9gAAAAJCTfYAAAAAAAAANgAAACgAAAAIAAAACAAAAAEAGAAAAAAAAAAAAMQOAADEDgAAAAAAAAAAAAD///9ZgABZgADzPz/zPz/zPz9AgP//gAD/gAD/AAD/AAD/AACKyub///+AAACAAAAAAP8AAP8AAP9AgP9ZgABZgABz13hz13hz13hAgP//gAD/gACA/wCA/wCA/wAA//+AAACAAAAAAP8AAP8AAP9AgP8L";
public TypeCategoryTab()
{
}
// Returns the properties of the specified component extended with
// a CategoryAttribute reflecting the name of the type of the property.
public override System.ComponentModel.PropertyDescriptorCollection GetProperties(object component, System.Attribute[] attributes)
{
PropertyDescriptorCollection props;
if( attributes == null )
props = TypeDescriptor.GetProperties(component);
else
props = TypeDescriptor.GetProperties(component, attributes);
PropertyDescriptor[] propArray = new PropertyDescriptor[props.Count];
for(int i=0; i<props.Count; i++)
{
// Create a new PropertyDescriptor from the old one, with
// a CategoryAttribute matching the name of the type.
propArray[i] = TypeDescriptor.CreateProperty(props[i].ComponentType, props[i], new CategoryAttribute(props[i].PropertyType.Name));
}
return new PropertyDescriptorCollection( propArray );
}
public override System.ComponentModel.PropertyDescriptorCollection GetProperties(object component)
{
return this.GetProperties(component, null);
}
// Provides the name for the property tab.
public override string TabName
{
get
{
return "Properties by Type";
}
}
// Provides an image for the property tab.
public override System.Drawing.Bitmap Bitmap
{
get
{
Bitmap bmp = new Bitmap(DeserializeFromBase64Text(img));
return bmp;
}
}
// This method can be used to retrieve an Image from a block of Base64-encoded text.
private Image DeserializeFromBase64Text(string text)
{
Image img = null;
byte[] memBytes = Convert.FromBase64String(text);
IFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream(memBytes);
img = (Image)formatter.Deserialize(stream);
stream.Close();
return img;
}
}
}
属性选项卡可以添加附加的属性选项卡以公开其默认属性集之外的属性信息。
ProvidePropertyAttribute 类
view plaincopy to clipboardprint?
ProvideProperty("MyProperty", typeof(Control))]
public class MyClass : IExtenderProvider {
protected CultureInfo ciMine = null;
// Provides the Get portion of MyProperty.
public CultureInfo GetMyProperty(Control myControl) {
// Insert code here.
return ciMine;
}
// Provides the Set portion of MyProperty.
public void SetMyProperty(Control myControl, string value) {
// Insert code here.
}
/* When you inherit from IExtenderProvider, you must implement the
* CanExtend method. */
public bool CanExtend(Object target) {
return(target is Control);
}
// Insert additional code here.
}
ProvideProperty("MyProperty", typeof(Control))]
public class MyClass : IExtenderProvider {
protected CultureInfo ciMine = null;
// Provides the Get portion of MyProperty.
public CultureInfo GetMyProperty(Control myControl) {
// Insert code here.
return ciMine;
}
// Provides the Set portion of MyProperty.
public void SetMyProperty(Control myControl, string value) {
// Insert code here.
}
/* When you inherit from IExtenderProvider, you must implement the
* CanExtend method. */
public bool CanExtend(Object target) {
return(target is Control);
}
// Insert additional code here.
}
在用此特性标记类时,即通知代码生成器使用所提供的名称创建扩展程序属性。所标记的类必须实现 IExtenderProvider。因此,新的属性可以由容器中的其他��件使用。
在所标记的类内,必须实现 Get<name> 和 Set<name> 方法。例如,如果用 [ProvideProperty("PropertyName")] 标记了某个类,则必须实现 GetPropertyName 和 SetPropertyName 方法。若要指定新属性将是扩展程序属性,则必须从 IExtenderProvider 实现,还必须实现 CanExtend 方法。
ReadOnlyAttribute 类
view plaincopy to clipboardprint?
[ReadOnly(true)]
public int MyProperty {
get {
// Insert code here.
return 0;
}
}
[ReadOnly(true)]
public int MyProperty {
get {
// Insert code here.
return 0;
}
}
定该属性 (Attribute) 所绑定到的属性 (Property) 在设计时是只读属性 (Property) 还是读/写属性 (Property)。无法继承此类
RefreshPropertiesAttribute 类
view plaincopy to clipboardprint?
[Category("Data")]
[Description("Indicates the source of data for the control.")]
[RefreshProperties(RefreshProperties.Repaint)]
[AttributeProvider(typeof(IListSource))]
public object DataSource
{
get
{
return this.dataGridView1.DataSource;
}
set
{
this.dataGridView1.DataSource = value;
}
}
[Category("Data")]
[Description("Indicates the source of data for the control.")]
[RefreshProperties(RefreshProperties.Repaint)]
[AttributeProvider(typeof(IListSource))]
public object DataSource
{
get
{
return this.dataGridView1.DataSource;
}
set
{
this.dataGridView1.DataSource = value;
}
}
RefreshPropertiesAttribute 指示在刷新 PropertyGrid 控件时要使用的刷新模式的类型
RunInstallerAttribute 类
view plaincopy to clipboardprint?
[RunInstallerAttribute(true)]
public class MyProjectInstaller : Installer {
// Insert code here.
}
[RunInstallerAttribute(true)]
public class MyProjectInstaller : Installer {
// Insert code here.
}
如果通过将 RunInstallerAttribute 设置为 true 标记从 Installer 继承的类,则在安装程序集时将调用 Visual Studio 自定义操作安装程序或 InstallUtil.exe。通过将 RunInstallerAttribute 设置为 false 标记的成员不会调用安装程序。默认为 false。
SettingsBindableAttribute 类
指定何时可将组件属性绑定到应用程序设置。
ToolboxItemAttribute 类
ToolboxItemAttribute 类提供了一种为 ToolboxItem 指定属性的方式。除了 Attribute 类提供的内容之外,此对象类还存储工具箱项的类型。
[ToolboxItem(typeof(MyToolboxItem))]
public class UserControl1 : UserControl
ToolboxItemFilterAttribute 类
view plaincopy to clipboardprint?
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
// This example contains an IRootDesigner that implements the IToolboxUser interface.
// This example demonstrates how to enable the GetToolSupported method of an IToolboxUser
// designer in order to disable specific toolbox items, and how to respond to the
// invocation of a ToolboxItem in the ToolPicked method of an IToolboxUser implementation.
namespace IToolboxUserExample
{
// This example component class demonstrates the associated IRootDesigner which
// implements the IToolboxUser interface. When designer view is invoked, Visual
// Studio .NET attempts to display a design mode view for the class at the top
// of a code file. This can sometimes fail when the class is one of multiple types
// in a code file, and has a DesignerAttribute associating it with an IRootDesigner.
// Placing a derived class at the top of the code file solves this problem. A
// derived class is not typically needed for this reason, except that placing the
// RootDesignedComponent class in another file is not a simple solution for a code
// example that is packaged in one segment of code.
public class RootViewSampleComponent : RootDesignedComponent
{
}
// The following attribute associates the SampleRootDesigner with this example component.
[DesignerAttribute(typeof(SampleRootDesigner), typeof(IRootDesigner))]
public class RootDesignedComponent : System.Windows.Forms.Control
{
}
// This example IRootDesigner implements the IToolboxUser interface and provides a
// Windows Forms view technology view for its associated component using an internal
// Control type.
// The following ToolboxItemFilterAttribute enables the GetToolSupported method of this
// IToolboxUser designer to be queried to check for whether to enable or disable all
// ToolboxItems which create any components whose type name begins with "System.Windows.Forms".
[ToolboxItemFilterAttribute("System.Windows.Forms", ToolboxItemFilterType.Custom)]
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
public class SampleRootDesigner : ParentControlDesigner, IRootDesigner, IToolboxUser
{
// This field is a custom Control type named RootDesignerView. This field references
// a control that is shown in the design mode document window.
private RootDesignerView view;
// This string array contains type names of components that should not be added to
// the component managed by this designer from the Toolbox. Any ToolboxItems whose
// type name matches a type name in this array will be marked disabled according to
// the signal returned by the IToolboxUser.GetToolSupported method of this designer.
private string[] blockedTypeNames =
{
"System.Windows.Forms.ListBox",
"System.Windows.Forms.GroupBox"
};
// IRootDesigner.SupportedTechnologies is a required override for an IRootDesigner.
// This designer provides a display using the Windows Forms view technology.
ViewTechnology[] IRootDesigner.SupportedTechnologies
{
get { return new ViewTechnology[] {ViewTechnology.Default}; }
}
// This method returns an object that provides the view for this root designer.
object IRootDesigner.GetView(ViewTechnology technology)
{
// If the design environment requests a view technology other than Windows
// Forms, this method throws an Argument Exception.
if (technology != ViewTechnology.Default)
throw new ArgumentException("An unsupported view technology was requested",
"Unsupported view technology.");
// Creates the view object if it has not yet been initialized.
if (view == null)
view = new RootDesignerView(this);
return view;
}
// This method can signal whether to enable or disable the specified
// ToolboxItem when the component associated with this designer is selected.
bool IToolboxUser.GetToolSupported(ToolboxItem tool)
{
// Search the blocked type names array for the type name of the tool
// for which support for is being tested. Return false to indicate the
// tool should be disabled when the associated component is selected.
for( int i=0; i<blockedTypeNames.Length; i++ )
if( tool.TypeName == blockedTypeNames[i] )
return false;
// Return true to indicate support for the tool, if the type name of the
// tool is not located in the blockedTypeNames string array.
return true;
}
// This method can perform behavior when the specified tool has been invoked.
// Invocation of a ToolboxItem typically creates a component or components,
// and adds any created components to the associated component.
void IToolboxUser.ToolPicked(ToolboxItem tool)
{
}
// This control provides a Windows Forms view technology view object that
// provides a display for the SampleRootDesigner.
[DesignerAttribute(typeof(ParentControlDesigner), typeof(IDesigner))]
internal class RootDesignerView : Control
{
// This field stores a reference to a designer.
private IDesigner m_designer;
public RootDesignerView(IDesigner designer)
{
// Perform basic control initialization.
m_designer = designer;
BackColor = Color.Blue;
Font = new Font(Font.FontFamily.Name, 24.0f);
}
// This method is called to draw the view for the SampleRootDesigner.
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
// Draw the name of the component in large letters.
pe.Graphics.DrawString(m_designer.Component.Site.Name, Font, Brushes.Yellow, ClientRectangle);
}
}
}
}
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
// This example contains an IRootDesigner that implements the IToolboxUser interface.
// This example demonstrates how to enable the GetToolSupported method of an IToolboxUser
// designer in order to disable specific toolbox items, and how to respond to the
// invocation of a ToolboxItem in the ToolPicked method of an IToolboxUser implementation.
namespace IToolboxUserExample
{
// This example component class demonstrates the associated IRootDesigner which
// implements the IToolboxUser interface. When designer view is invoked, Visual
// Studio .NET attempts to display a design mode view for the class at the top
// of a code file. This can sometimes fail when the class is one of multiple types
// in a code file, and has a DesignerAttribute associating it with an IRootDesigner.
// Placing a derived class at the top of the code file solves this problem. A
// derived class is not typically needed for this reason, except that placing the
// RootDesignedComponent class in another file is not a simple solution for a code
// example that is packaged in one segment of code.
public class RootViewSampleComponent : RootDesignedComponent
{
}
// The following attribute associates the SampleRootDesigner with this example component.
[DesignerAttribute(typeof(SampleRootDesigner), typeof(IRootDesigner))]
public class RootDesignedComponent : System.Windows.Forms.Control
{
}
// This example IRootDesigner implements the IToolboxUser interface and provides a
// Windows Forms view technology view for its associated component using an internal
// Control type.
// The following ToolboxItemFilterAttribute enables the GetToolSupported method of this
// IToolboxUser designer to be queried to check for whether to enable or disable all
// ToolboxItems which create any components whose type name begins with "System.Windows.Forms".
[ToolboxItemFilterAttribute("System.Windows.Forms", ToolboxItemFilterType.Custom)]
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
public class SampleRootDesigner : ParentControlDesigner, IRootDesigner, IToolboxUser
{
// This field is a custom Control type named RootDesignerView. This field references
// a control that is shown in the design mode document window.
private RootDesignerView view;
// This string array contains type names of components that should not be added to
// the component managed by this designer from the Toolbox. Any ToolboxItems whose
// type name matches a type name in this array will be marked disabled according to
// the signal returned by the IToolboxUser.GetToolSupported method of this designer.
private string[] blockedTypeNames =
{
"System.Windows.Forms.ListBox",
"System.Windows.Forms.GroupBox"
};
// IRootDesigner.SupportedTechnologies is a required override for an IRootDesigner.
// This designer provides a display using the Windows Forms view technology.
ViewTechnology[] IRootDesigner.SupportedTechnologies
{
get { return new ViewTechnology[] {ViewTechnology.Default}; }
}
// This method returns an object that provides the view for this root designer.
object IRootDesigner.GetView(ViewTechnology technology)
{
// If the design environment requests a view technology other than Windows
// Forms, this method throws an Argument Exception.
if (technology != ViewTechnology.Default)
throw new ArgumentException("An unsupported view technology was requested",
"Unsupported view technology.");
// Creates the view object if it has not yet been initialized.
if (view == null)
view = new RootDesignerView(this);
return view;
}
// This method can signal whether to enable or disable the specified
// ToolboxItem when the component associated with this designer is selected.
bool IToolboxUser.GetToolSupported(ToolboxItem tool)
{
// Search the blocked type names array for the type name of the tool
// for which support for is being tested. Return false to indicate the
// tool should be disabled when the associated component is selected.
for( int i=0; i<blockedTypeNames.Length; i++ )
if( tool.TypeName == blockedTypeNames[i] )
return false;
// Return true to indicate support for the tool, if the type name of the
// tool is not located in the blockedTypeNames string array.
return true;
}
// This method can perform behavior when the specified tool has been invoked.
// Invocation of a ToolboxItem typically creates a component or components,
// and adds any created components to the associated component.
void IToolboxUser.ToolPicked(ToolboxItem tool)
{
}
// This control provides a Windows Forms view technology view object that
// provides a display for the SampleRootDesigner.
[DesignerAttribute(typeof(ParentControlDesigner), typeof(IDesigner))]
internal class RootDesignerView : Control
{
// This field stores a reference to a designer.
private IDesigner m_designer;
public RootDesignerView(IDesigner designer)
{
// Perform basic control initialization.
m_designer = designer;
BackColor = Color.Blue;
Font = new Font(Font.FontFamily.Name, 24.0f);
}
// This method is called to draw the view for the SampleRootDesigner.
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
// Draw the name of the component in large letters.
pe.Graphics.DrawString(m_designer.Component.Site.Name, Font, Brushes.Yellow, ClientRectangle);
}
}
}
}
ToolboxItemFilterAttribute 提供一种机制,通过这种机制,可以将工具箱项标记为只能与具有匹配的属性或者代码的设���器一起使用,这些属性或者代码确定了该项在工具箱中应该启用还是禁用。
可以将 ToolboxItemFilterAttribute 应用到 ToolboxItem 以指示筛选器字符串和筛选器类型,以便指定何时启用或禁用项。还可以将 ToolboxItemFilterAttribute 应用到设计器,以指示在工具箱中启用项的要求。这一类型的属性可以使用来表明,某个工具箱项只有在使用带匹配筛选器字符串的设计器时才能启用。筛选器的类型在 FilterType 属性中由 ToolboxItemFilterType 来指示,它指示是否使用筛选器字符串匹配以及如何使用,或者是否使用自定义代码来确定是否启用项。
TypeConverterAttribute 类
view plaincopy to clipboardprint?
[TypeConverter(typeof(MyClassConverter))]
public class MyClass {
// Insert code here.
}
[TypeConverter(typeof(MyClassConverter))]
public class MyClass {
// Insert code here.
}
用于转换的类必须从 TypeConverter 继承。使用 ConverterTypeName 属性 (Property) 来获取为该属性 (Attribute) 所绑定到的对象提供数据转换的类名。
有关属性的更多信息,请参见 属性 (Attribute) 概述 和 利用属性扩展元数据。有关类型转换器的更多信息,请参见 TypeConverter 基类和 如何:实现类型转换器。
TypeDescriptionProviderAttribute 类
此属性为开发人员提供了一种为其所编写的类提供自定义元数据的方法。此功能扩展了 TypeDescriptor 类中的静态类型信息功能,默认情况下,该类只从已编译的类的元数据中直接获得类型信息。
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/aofengdaxia/archive/2010/10/06/5924364.aspx