用ASP.NET创建自定义文本框(2)
点击次数:25 次 发布日期:2008-11-26 15:02:54 作者:源代码网
|
源代码网推荐 源代码网推荐 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: } 源代码网推荐 源代码网推荐 其中第3行的目的是,调用基类,继承原有的文本框的属性。AddAttributesToRender的方法使用HtmlTextWriter流作为参数。在第9,第12行,分别通过调用HTML文本流的AddAttribute方法增加其客户端的输出。其中传入了两个参数,第一个参数是HTML的属性,第二个是属性对应的值。它们经过浏览器输出后,变为<input type="text" onBlur="JavaScript...">的形式。 源代码网推荐 源代码网推荐 因为浏览器使用的是十六进制的颜色,所以我们采用ColorTranslator类去将.NET的颜色类型转换为浏览器中能识别的颜色类型(第7和第12行)。在第8行,先检查_coloroff属性是否没被赋值,如果没赋值,则backcoloroff的颜色设置为原来文本框的背景色。 源代码网推荐 源代码网推荐 而在第5行,我们检查浏览器的类型是否支持onfocus和onblur事件,并且由于想在VS.NET的设计时就能对控件的属性进行改变,所以增加了一个判断的函数indesignmode: 源代码网推荐 源代码网推荐 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: } 源代码网推荐 源代码网推荐 在上面代码的第4行,通过判断如果HttpContext实例是否为null,如果为null的话,则证明当前是处于VS.NET的设计模式下,没响应HTTP请求。接下来,我们测试一下所做的控件。 源代码网推荐 做人要厚道,请注明转自酷网动力(www.ASPCOOL.COM)。 源代码网推荐 源代码网供稿. |
