技术开发 频道

Asp.net控件开发之创建控件

  标签(Attribute)

  也许你已经对上面代码的[ToolboxData("<{0}:textbox3d runat=server>")]感到很迷惑,其实这是C#特有的一种类型。Attribute的本质是一种用于修改其他类的属性或方法的类,其实Attribute本身就是一种类,所有的Attribute都会直接或者间接的继承于System.Attribute,像接口的名称往往以大写的I开头一样,标签的结尾习惯上以Attribute结尾,这样可以增加可读性.简单的示例如下:

public class SampleAttribute : Attribute

    {

}

  注意,所有的标签(Attribute)都必须被声明为public.

  在使用时可以像这样:

public class SampleClass

    {

        [SampleAttribute]

        
public virtual void SampleMethod()

        {

            
//...

        }

}

  在应用的时候,你可以针对一个类,方法或者属性应用好几个Attribute.应用方法可以将这些都写入一个方括号中,就像这样:

[DefaultProperty("Text"), toolboxdata("<{0}:mylabel runat=server></{0}:mylabel>")]

  也可以分别写在几个不同的方括号中,就像这样:

[DefaultProperty("Text")]

    [ToolboxData("
<{0}:mylabel runat=server></{0}:mylabel>")]

  Visual Studio控件开发常用的标签(Attribute)

  在利用Visual Studio进行控件开发时,利用Attribute特性可以让空间更加智能,比如当你双击控件时,默认会进入控件的哪个事件的EventHandler,或者当你从ToolBox里拽过来你开发的控件,默认在前台会生成什么样的代码片段等.这些都可以利用Attribute做到.这些常用的属性都被定义在System.ComponentModel命名空间中,下面是这个命名空间里的常用的Attribute.

Attribute

描述

BindableAttribute

Indicates whether or not a property supports two-way

data binding

BrowsableAttribute

Indicates whether or not a property or event should be listed in a property browser

DefaultEvent

Specifies the name of the default event for a class

DescriptionAttribute

Allows the property browser to display a brief description of a property

ToolboxData

Specifies default values for control attributes and customizes the initial HTML content

EditorAttribute

Associates a UI type editor with a property

DefaultProperty

Specifies the name of the default property for a class

查看原文

0
相关文章