標籤:des blog http os io 使用 ar 檔案 2014
最近看了MSDN關於自訂控制項的介紹,根據官方的文檔,自己學著做了一個簡單的Demo給需要的朋友參考。
ASP.NET 源生的TextBox是不帶Label標籤的,這裡我要實現的是建立一個帶Label標籤的TextBox,並且預設填充Text值為GUID(唯讀)
實際上現在很多第三方組件都有這種控制項,如Ext.Net,FineUI等等。這裡只是為了學習瞭解自訂控制項的開發。
步入正題
1.在VS2010中建立一個類庫項目,我選擇的架構是3.5。名稱“MyTextBoxControl”
2.然後建立一個類檔案,名稱“MyTextBoxControl.cs”
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Web;using System.ComponentModel;using System.Web.UI;using System.Web.UI.WebControls;using System.Security.Permissions;namespace MyTextBoxControl{ [ AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal), AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal), DefaultProperty("Text"), ToolboxData("<{0}:MyTextBoxControl runat=\"server\"> </{0}:MyTextBoxControl>") ] public class MyTextBoxControl : TextBox//繼承源生TextBox { /// <summary> /// 為TextBox擴充的Label標籤 /// </summary> [ Bindable(true), Category("Appearance"), DefaultValue("Label1:"), Description("The control content text."), Localizable(true) ] public virtual string Label { get { string s = (string)ViewState["Label"]; return (s == null) ? "Label1:" : s;//如果控制項Label為空白,預設值為"Label1" } set { ViewState["Label"] = value; } } /// <summary> /// 重繪控制項 /// </summary> /// <param name="writer"></param> protected override void Render(System.Web.UI.HtmlTextWriter writer) { System.Web.UI.WebControls.Label lable = new Label(); lable.ID = "Label1"; lable.Text = this.Label;//設定標籤文本 lable.Font.Bold = true;//設定文本顯示為粗體 lable.RenderControl(writer);//將Label輸出到控制項中 this.Width = Unit.Pixel(255);//設定預設寬度 this.Text = Guid.NewGuid().ToString("N").ToUpper();//預設文本,設定預設Text值 this.ReadOnly = true;//設定Text預設唯讀 base.Render(writer);//輸出控制項 } }}
編譯項目,會在Debug目錄下產生MyTextBoxControl.dll檔案
3.建立一個網站項目測試自訂控制項,項目名稱“TestControl”先引用剛才的控制項
在VS2010菜單上選擇“工具”》“選擇工具箱”選擇MyTextBoxControl.dll所在目錄,確定
然後在VS2010的工具列上會出現剛才添加的控制項了
接著大家就可以像其他控制項一樣拖動使用了,請看下面的
這裡Label屬性預設為空白,我們可以設定成其他值。最後上一張運行圖
我這個Demo做的比較簡單,只是入門。更複雜的官方文檔有很詳細的介紹 有興趣的朋友可以多研究下http://msdn.microsoft.com/zh-cn/library/bb386519(v=vs.90).aspx
Demo下載
ASP.NET自訂控制項入門Demo