扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
using System.Drawing;
line 1: [assembly: TagPrefix ( "ControlLib" , "lib" )]
line 2: namespace ControlLib
line 3: {
line 4: [DefaultProperty( "BackColorOn" ),
line 5: ToolboxData( "<{0}:PimpedOutTextbox runat=server></{0}:PimpedOutTextbox>" )]
line 6: public class PimpedOutTextbox : System.Web.UI.WebControls.TextBox
line 7: {
在一开始,增加了assembly属性,其目的是,当在vs.net中拖拉该控件时,VS.net会自动添加Tagprefix的控件标记。在pimedouttexbox类中,增加了几个属性:defaultproperty和toolboxdata.defaultproperty中的属性backcoloron的含义是,当把该控件从VS.NET的工具箱拖拉到设计器时,该控件中被默认选定的属性。Toolboxdata属性是和[assembly:Tagprefix]属性相关,用来表明该控件是如何从HTML视图中产生的。这些属性将在下文详细讲解。
最后,在第6行,注意 public class PimpedOutTextbox : System.Web.UI.WebControls.TextBox 一句,其中表明这个控件是比原来的文本框控件增加了新的行为。总的来说,我们创建的这个控件依然是一个文本框控件,只不过是继承了原有文本框控件的属性和行为,并且有自己的新的属性而已。
下一步,将给pimedouttextbox控件新增两个属性。其中,我们设想,当用户在文本框中输入或者文本框获得焦点时,文本框的颜色有变化,所以命名新的属性BackColoron;当控件失去焦点时,文本框的颜色命名为backcoloroff。
line 1: private Color _colOff;
line 2: [Category( "Appearance" ), Description( "The background
color when the control loses focus" )]
line 3: public Color BackColorOff
line 4: {
line 5: get{return _colOff;}
line 6: set{_colOff = value
line 7: }
line 8: private Color _colOn;
line 9: [Category( "Appearance" ), Description( "The background
color when the control has the focus" )]
line 10: public Color BackColorOn
line 11: {
line 12: get{return _colOn; }
line 13: set{_colOn = value;}
line 14: }
上面的代码,是典型的对属性的赋值和存取的语句了,相信大家都很熟悉了。要提及一点的是,第2行和第9行的category和descriptiton属性,是该控件的属性窗口中,对backcoloron和backcoloroff两个属性的一个描述。注意,我们使用了color类,这样比较方便,可以用vs.net自带的颜色选择器,而不用输入颜色的十六进制值。
接着,下面是比较重要的部分。在这个新的控件, 我们将用重载一个AddAttributesToRender()的方法输出新的内容到浏览器中。其中,将加入对客户端的onfocus和onblur事件的响应。另外,要注意的是,当在VS.NET创建该控件时,会自动调用该方法,所以我们可以在设计期间对其中的属性进行设置。
line 1: protected override void AddAttributesToRender( HtmlTextWriter writer )
line 2: {
line 3: base.AddAttributesToRender( writer );
line 4: //only add the client-side javascript for design mode or IE
line 5: if( inDesignMode() || System.Web.HttpContext.Current.Request.Browser.Type.IndexOf( "IE" ) > -1 )
line 6: {
line 7: writer.AddAttribute( "onFocus", "JavaScript:this.style.backgroundColor=@#" + ColorTranslator.ToHtml( _colOn ) + "@#;" );
line 8: if( _colOff.Equals( Color.Empty ) )
line 9: {
line 10: _colOff = this.BackColor;
line 11: }
line 12: writer.AddAttribute( "onBlur", "JavaScript:this.style.backgroundColor=@#" + ColorTranslator.ToHtml( colOff ) + "@#;" );
line 13: }
line 14: }
line 1: private bool inDesignMode()
line 2: {
line 3: bool blnOut = false;
line 4: if( object.ReferenceEquals( System.Web.HttpContext.Current, null ) )
line 5: {
line 6: blnOut = true;
line 7: }
line 8: else
line 9: {
line 10: blnOut = false;
line 11: }
line 12: return blnOut;
line 13: }
<%@ Register TagPrefix="lib" Namespace="ControlLib" Assembly="ControlLib" %>
[assembly: TagPrefix ( "ControlLib" , "lib" )]
JavaScript:debugger;this.style.backgroundColor=@#blue@#;
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。