自訂 Web 伺服器控制項

來源:互聯網
上載者:User
文章目錄
  • 控制項的繪製過程
  • 使用自訂Web伺服器控制項

MSDN中關於本節內容的演練:http://msdn.microsoft.com/zh-cn/library/yhzc935f(v=vs.100).aspx

微軟的介紹已經足夠詳盡,我這裡只是簡單的說一下如何自訂Web 伺服器控制項。步驟大致如下:

  1. 建立一個控制項類,使其繼承自WebControl或要擴充的其它控制項(例如 Button、TextBox等)
  2. 添加一些自己需要的屬性和方法,然後重寫Render、AddAttribute方法,使其可以在用戶端展示。
  3. 功能完善以後,編譯項目,在需要引用的地方添加Web.Config的配置項,使其可以正常的工作。

就拿MSDN中的演練來說,我們可以建立一個空的web項目,然後添加一個Controls目錄(為了階層,不是必須的),然後建立一個Web Control的類,名字為WelcomeLabel,代碼如下:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Linq;using System.Security.Permissions;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace SampleCustomWebControl.Controls{    [        AspNetHostingPermission(SecurityAction.Demand,            Level = AspNetHostingPermissionLevel.Minimal),        AspNetHostingPermission(SecurityAction.InheritanceDemand,            Level = AspNetHostingPermissionLevel.Minimal),        DefaultProperty("Text"),        ToolboxData("<{0}:WelcomeLabel runat=\"server\"> </{0}:WelcomeLabel>")    ]    public class WelcomeLabel : WebControl    {        [            Bindable(true),            Category("Appearance"),            DefaultValue(""),            Description("The welcome message text."),            Localizable(true)        ]        public virtual string Text        {            get            {                string s = (string)ViewState["Text"];                return (s == null) ? String.Empty : s;            }            set            {                ViewState["Text"] = value;            }        }        protected override void RenderContents(HtmlTextWriter writer)        {            writer.WriteEncodedText(Text);            if (Context != null)            {                string s = Context.User.Identity.Name;                if (s != null && s != String.Empty)                {                    string[] split = s.Split('\\');                    int n = split.Length - 1;                    if (split[n] != String.Empty)                    {                        writer.Write(", ");                        writer.Write(split[n]);                    }                }            }            writer.Write("!");        }    }}

完全的微軟的代碼,沒有什麼改動。需要說一下的是,上面的一堆特性主要是為了在設計時使用的。

這裡推薦從WebControl繼承,而不是直接從Control類繼承,因為WebControl 類從 Control 派生,並添加了與樣式相關的屬性,如 Font、ForeColor 和 BackColor。更貼近我們的使用習慣。

控制項的繪製過程

在這個例子中,由於只設定了Text屬性,並且是作為控制項內容來呈現的,所以只需要重寫RenderContents就可以了。

控制項在繪製的過程中,先調用Render方法,在Render方法中再調用RenderBeginTag、RenderContents和RenderEndTag方法。RenderBeginTag和RenderEndTag 方法是繪製標籤的開始和結束的,他們依賴與TagName欄位,只要重寫了類的TagName欄位,這兩個方法就沒有必要進行重寫了。

如果需要向控制項中添加一些屬性,則需要重寫AddAttributesToRender方法。

使用自訂Web伺服器控制項

將項目編譯為.dll檔案以後,在web項目中引用。

添加webConfig的配置:

      <pages>        <controls>          <add tagPrefix="cc" namespace="SampleCustomWebControl.Controls" assembly="SampleCustomWebControl" />        </controls>      </pages>

在頁面中使用:

<cc:WelcomeLabel ID="lblWelcome" runat="server" Text="歡迎訪問"></cc:WelcomeLabel>

程式中也可以動態改變其Text屬性:

lblWelcome.Text = "歡迎訪問,伺服器時間:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.