Intro
廢話少說XD,網頁就是要不斷 Add/Edit/View...
明明同一個Layout為何要做一個編輯, 一個檢視咧.
基於這個想法, 就試著做一個切換方式吧!!
重點在 override Render
Summary
1. 建一個interface IViewEditControl 讓控制項有共同 function
2. 繼承原生控制項, 實作咱們的interface, 並覆寫Render
3. 切換模式吧!!
Context
架構~
1. 這是咱的 IViewEditControl.cs, 就只是Set/Get ViewEdit Mode
namespace WebCtrl { //模式 public enum ViewEditControlMode { Edit, View } //Interface public interface IViewEditControl { void SetVeMode(ViewEditControlMode mode); ViewEditControlMode GetVeMode(); } }
2. WcViewEditDropDownList.cs, 儲存Mode, 覆寫Render, 請看Code說明~
WcViewEditTextbox.cs 很類似, 就不貼了, 當作業吧!(被砸)
namespace WebCtrl { //繼承DropDownList, 實作IViewEditControl public class WcViewEditDropDownList : System.Web.UI.WebControls.DropDownList, IViewEditControl { //重點, 覆寫Render protected override void Render(System.Web.UI.HtmlTextWriter writer) { //若是View, 直接輸出 if (this.m_veMode == ViewEditControlMode.View) { writer.Write(this.SelectedItem.Text); } else//否則執行原本的Render { base.Render(writer); } } #region IViewEditControl //要儲存Mode ViewEditControlMode m_veMode = ViewEditControlMode.Edit; void IViewEditControl.SetVeMode(ViewEditControlMode mode) { this.m_veMode = mode; } ViewEditControlMode IViewEditControl.GetVeMode() { return this.m_veMode; } #endregion } }
就醬,完成了
===我不是分隔線==============================
3. 範例
Page(Default.aspx) 加入註冊控制項
<%@ Register Namespace="WebCtrl" TagPrefix="mytag" %>
再加入咱們的控制項
Name: <mytag:WcViewEditTextBox ID="tbName" runat="server"></mytag:WcViewEditTextBox> <br /> Sex: <mytag:WcViewEditDropDownList ID="ddlSex" runat="server"> </mytag:WcViewEditDropDownList>
Page.cs(Default.aspx.cs)
protected void Page_Load(object sender, EventArgs e) { #region Data ddlSex.DataSource = new ListItem[] { new ListItem("Girl","0"), new ListItem("Boy","1") }; ddlSex.DataBind(); tbName.Text = "Ellin"; ddlSex.SelectedValue = "0"; #endregion //切換模式 switch (Request["mode"]) { case "View": SetVeMode(WebCtrl.ViewEditControlMode.View, this); break; case "Edit": SetVeMode(WebCtrl.ViewEditControlMode.Edit, this); break; } } //Set Mode public static void SetVeMode(WebCtrl.ViewEditControlMode mode, System.Web.UI.Control ctrl) { foreach (System.Web.UI.Control loop in ctrl.Controls) { if (loop is WebCtrl.IViewEditControl) { (loop as WebCtrl.IViewEditControl).SetVeMode(mode); } SetVeMode(mode, loop); } }
在網址列加入QueryString即可 (ex: Default.aspx?mode=View)
The End...
對Label、TextBox的控制項而言這個方法不錯,
回覆刪除不過DropDownList直接write在UI上看會不會怪怪的XD
還是說這比較像是對在產出report報表上比較方便?
感謝分享~