面板曲线容器 ASP.NET 自定义控件核

分享于 

27分钟阅读

Web开发

  繁體

介绍

我想拥有一个可以作为容器工作的控件,并且使用类似于 System.Web.UI.WebControls.Panel <ASP:PANEL> 它是弯曲的,同时又有自己的自定义标题文本。

进程

我在互联网上搜索了很多类似 Panel 控件的控件,但从未得到任何帮助。 所以我决定自己做一个。 这样做会造成用户控件产生曲线,并要求开发人员将值传递给开发人员,这使得整个过程变得复杂,因为我不想将所有代码放在用户控件中,只是为了生成边界。 Finally示例讨论了这种实现,如果控件在用户控件或者 DataGrid 中使用了控件,则会抛出错误。 然后,我创建了自己的控件,并在用户控件。DataGrid。嵌套 DataGrid 以及它的他方面成功地测试了它。

功能

这里控件可以使用以下功能:

  • 弧形选项卡头。
  • 最小化 icon 以最小化标签。
  • 打印 icon 以打印选定的内核。
  • 你可以自定义页眉中显示的标题文本。
  • 你可以更改顶部选项卡或者底部主体的背景颜色。
  • 你可以在容器中使用用户控件。自定义控件或者任何web控件,但仍然可以在后面的代码中直接访问这些控件。

    在后面的代码中:

    protected TextBox txt;

    在aspx中:

    <Tittle:PanelCurveControl...><asp:textboxid=txt .../></Tittle:PanelCurveControl>
  • 这里控件将在 postback 期间保持它的最小化/最大化状态。
  • 这里控件可以在 DataGrid 或者用户控件( 父控件的id在子控件的前面加上前缀) 中使用,无任何问题。

如何使用它

如果使用过 <asp:panel>,则可以使用这里自定义控件:

<Tittle:PanelCurveControlID=
"Panelcurvecontrol1"runat="server"Title="My first Panel"> Name:<br><asp:textboxid=txt runat="server"/></Tittle:PanelCurveControl>

上面的内容将呈现为:

属性

  • Expandable: 根据需要使控件可以扩展。 默认值: true
  • RenderInBox: 在框中呈现内容。 默认值 false ( 仅当 Expandablefalse )。制作 Expandabletrue 使选项卡消失,但如果 Expandablefalse :
  • RenderInBox 进行" true "显示容器的边框。
  • RenderInBox 进行" false "显示无边框。
  • Closed: 可以扩展面板的内容是否必须可见。
  • Title: 显示为可以扩展面板标题的文本。
  • Margin: 面板可以扩展时使用的边距。
  • HasMinimize: 是否在屏幕上显示最小化 icon。
  • HasPrint: 是否在屏幕上显示打印 icon。
  • DefaultMinimize: 默认情况下将它的最小化。
  • BodyBackColor: 内容背面颜色。
  • TabBackColor: 顶部选项卡背面颜色。
  • HeaderTextColor: 顶部页眉文本颜色。

一些技术细节

我从 ASP:Panel 继承这个控件,以便它可以与 Panel 相同的方式使用。 我并没有从 INamingContainer 继承它,原因是我不希望它在子控件 every ( 如果控件在网格或者用户控件中使用,则会出现问题) 之前前前前缀。 隐藏字段用于在回发过程中保留它的最小化/最大化状态。 我修复了一个隐藏的字段 in,以便它在普通页面和任何控件中维护状态。

if ( this.UniqueID.IndexOf(":") >=0 )
 hdn.ID = this.ID + "_hdnMinimizeState"; 
 //Within some user control or grid //E.g. client id will be in this case //"UserControl1__ctl0_tblCrvPnlControl2_hdnMinimizeState"else hdn.ID = this.UniqueID + "_hdnMinimizeState"; 
 //Straight on aspx page, //E.g. client id will be in this case //"tblCrvPnlControl1_hdnMinimizeState"

PanelCurveControl.cs

using System;using System.ComponentModel;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Drawing;using System.IO;using System.Collections.Specialized;
[assembly: TagPrefix ("Tittle.Controls", "Tittle") ]namespace Tittle.Controls
{ 
 #region Table Curve Panel Control (Expandable)///<summary>/// Renders a tab control on page. i.e. A tabbed /// image on top of the table and you can have ur own /// contents in between that.///<example>///<code>///<Tittle:PanelCurveControlrunat="server"///Expandable="true"///Width="500px"///Margin="10"///Title="Employees">///<tableborder=1>///<tr><td>test1</td><td>test2</td></tr>///<tr><td>test3</td><td>test4</td></tr>///</table>///</Tittle:PanelCurveControl>///</CODE>///</EXAMPLE>///<AUTHOR>Tittle Joseph (tittlejoseph@yahoo.com) India.</AUTHOR>///<URL>http://www.codeproject.com/PanelCurveContainer/</URL>///</SUMMARY> [ToolboxData(
 "<{0}:PanelCurveControl runat=
"server" Expandable='true' id='tblCrvPnl' Width='200px'>")]
 publicclass PanelCurveControl : Panel, IPostBackDataHandler 
 {
 privatestring skinName = ""; //"/BasicNuggetSkin"; privatebool hasMinimize = true;
 privatebool hasPrint = true; 
 privatestring imgPath;
 private Color bodyBackColor = Color.Transparent;
 privatestring tabBackColor = "#99CCFF";
 privatestring headerTextColor = "black";
 public PanelCurveControl() : base()
 { 
 Expandable = true;
 RenderInBox = false;
 Title = "Panel";
 Font.Name = "verdana";
 Font.Size = FontUnit.Point(10);
 Margin = 2;
 Closed = false; 
 ForeColor = Color.Black;
 BorderColor = Color.DodgerBlue; 
 imgPath = 
 HttpContext.Current.Request.ApplicationPath + 
 skinName + "/Images/";
 //imgPath ="/Images/"; }
 ///<SUMMARY>/// Makes the control expandable on demand, /// Default: true///</SUMMARY> [Browsable(true),
 Category("Validation"),
 DefaultValue("true"),
 Description ("Makes the control expandable on demand.") ] 
 publicbool Expandable
 {
 get {return Convert.ToBoolean(ViewState["Expandable"]);}
 set {ViewState["Expandable"] = value;}
 } 
 ///<SUMMARY>/// Render the contents in the box /// (used only if Expandable is false),////// Expandable true makes tab disappear, /// but if Expandable is false /// RenderInBox is"true" shows border of container./// RenderInBox is"false" no border appears./// Default: false///</SUMMARY> [Browsable(true),
 Category("Misc"),
 DefaultValue("false"),
 Description ("Render the contents in the box.") ]
 publicbool RenderInBox
 {
 get {return Convert.ToBoolean(ViewState["RenderInBox"]);}
 set {ViewState["RenderInBox"] = value;}
 }
 ///<SUMMARY>/// Whether the contents of the expandable panel must be visible /// Equivalent to"DefaultMinimize" attribute/// Default: false///</SUMMARY> [Browsable(true),
 Category("Validation"),
 DefaultValue("false"),
 Description ("Whether the contents of the" + 
 "expandable panel must be visible.") ] 
 publicbool Closed
 {
 get {return Convert.ToBoolean(ViewState["Closed"]);}
 set {ViewState["Closed"] = value;}
 } 
 ///<SUMMARY>/// The text displayed as the caption of the expandable panel ////// Default:"Panel"///</SUMMARY> [Browsable(true),
 Category("Behavior"),
 DefaultValue("Panel"),
 Description ("The text displayed as the" + 
 "caption of the expandable panel.") ]
 publicstring Title
 {
 get {return Convert.ToString(ViewState["Title"]);}
 set {ViewState["Title"] = value;}
 }
 ///<SUMMARY>/// The margin to use if the panel is expandable ////// Default:"2"///</SUMMARY> [Browsable(true),
 Category("Appearance"),
 DefaultValue("2"),
 Description ("Margin to use if the panel is expandable.") ]
 publicint Margin
 {
 get {return Convert.ToInt32(ViewState["Margin"]);}
 set {ViewState["Margin"] = value;}
 } 
 ///<SUMMARY>/// SkinName to be used in nugget i.e."BasicNuggetSkin", ///"BillInfoNuggetSkin","DataGridNuggetSkin", ///"TabbedNuggetSkin"////// Default is"BasicNuggetSkin"///</SUMMARY> [Browsable(true),
 Category("Behavior"),
 DefaultValue("BasicNuggetSkin"),
 Description ("Skinname to be used in nugget.") ]
 publicstring SkinName
 {
 get{ return skinName;}
 set{ skinName = value;}
 }
 ///<SUMMARY>/// Whether to show Minimize icon on screen or not.////// Default: true///</SUMMARY> [Browsable(true),
 Category("Validation"),
 DefaultValue("true"),
 Description ("Whether to show minimize" + 
 "icon on screen or not.") ]
 publicbool HasMinimize
 {
 get{ return hasMinimize;}
 set{ hasMinimize = value;}
 }
 ///<SUMMARY>/// Whether to show Print icon on screen or not.////// Default: true///</SUMMARY> [Browsable(true),
 Category("Validation"),
 DefaultValue("true"),
 Description ("Whether to show Print" + 
 "icon on screen or not.") ]
 publicbool HasPrint
 {
 get{ return hasPrint;}
 set{ hasPrint = value;} 
 }
 ///<SUMMARY>/// Render it minmized by default or not////// Default: false///</SUMMARY> [Browsable(true),
 Category("Appearance"),
 DefaultValue("false"),
 Description ("Render it minimized by default or not.") ]
 publicbool DefaultMinimize
 {
 get{ return Closed;}
 set{ Closed = value;}
 }
 ///<SUMMARY>/// Content Back Color///</SUMMARY>public Color BodyBackColor
 {
 get { return bodyBackColor; }
 set { bodyBackColor = value; }
 }
 ///<SUMMARY>/// Top Tab Back Color///</SUMMARY>publicstring TabBackColor
 {
 get { return tabBackColor; }
 set { tabBackColor = value; }
 }
 ///<SUMMARY>/// Top Header Text Color///</SUMMARY>publicstring HeaderTextColor
 {
 get { return headerTextColor; }
 set { headerTextColor = value; }
 }
 ///<SUMMARY>///RaisePostDataChangedEvent::LoadPostData/// Automatically updates the Closed property based on the content/// of hidden field named as this control ///</SUMMARY>///<PARAMname="postDataKey"</PARAM>///<PARAMname="postCollection"></PARAM>///<RETURNS></RETURNS>publicvirtualbool LoadPostData(string postDataKey, 
 NameValueCollection postCollection) 
 {
 bool currentValueOfClosed = Closed;
 bool postedValueOfClosed = 
 Convert.ToBoolean(postCollection[postDataKey+
 "_hdnMinimizeState"]);
 // What if the field is empty?if (!currentValueOfClosed.Equals(postedValueOfClosed)) 
 {
 Closed = postedValueOfClosed;
 returntrue;
 }
 returnfalse;
 } 
 ///<SUMMARY>/// IPostBackDataHandler::RaisePostDataChangedEvent ///</SUMMARY>publicvirtualvoid RaisePostDataChangedEvent() 
 {
 // Do nothing here// No need of firing server-side events } 
 ///<SUMMARY>/// Fires when the panel gets loaded///</SUMMARY>///<PARAMname="e"></PARAM>protectedoverridevoid OnLoad(EventArgs e)
 {
 base.OnLoad(e); 
 // Check the browser caps and disable collapse/expand if neededbool uplevel = false;
 HttpBrowserCapabilities caps = Page.Request.Browser;
 if (caps.Browser.ToUpper().IndexOf("IE") > -1)
 {
 // This is IE. But is it at least v5?if (caps.MajorVersion> 4)
 uplevel = true;
 }
 // If the browser is not IE5 or higher, drop collapse/expand if (!uplevel)
 {
 Expandable = false;
 RenderInBox = true;
 }
 //Need to write this, so that LoadPostData() gets called. Page.RegisterRequiresPostBack(this);
 }
 ///<SUMMARY>/// Render the control///</SUMMARY>///<PARAMname="output"></PARAM>protectedoverridevoid Render(HtmlTextWriter output) 
 {
 if (!Expandable)
 {
 if (!RenderInBox)
 base.Render(output);
 else RenderContentsInBox(output);
 return;
 }
 // Add margin information if the panel is expandable Style["margin"] = Margin.ToString();
 Style["display"] = (Closed?"none" :"");
 // The internal panel must cover 100% of the parent area// irrespective of the physical width. We change this here// so that the original Panel code doesn't reflect the// external width. Unit oldWidth = Width;
 Width = Unit.Percentage(100);
 //Add Hidden Field to maintain //minimize/maximize state of the curve. TextBox hdn = new TextBox();
 hdn.Attributes.Add("style","display:none");
 //This is what created a big nuisance to meif ( this.UniqueID.IndexOf(":") >=0 )
 hdn.ID = this.ID + "_hdnMinimizeState"; 
 //"UserControl1__ctl0_tblCrvPnlControl2_hdnMinimizeState"else hdn.ID = this.UniqueID + "_hdnMinimizeState"; 
 //"tblCrvPnlControl1_hdnMinimizeState" hdn.Text = Closed.ToString();
 this.Controls.Add(hdn);
 // Capture the default output of the Panel StringWriter writer = new StringWriter();
 HtmlTextWriter buffer = new HtmlTextWriter(writer);
 base.Render(buffer);
 string panelOutput = writer.ToString();
 // Restore the wanted width because this affects the outer table Width = oldWidth;
 BuildControlTree(output, this.ClientID, panelOutput);
 return;
 } 
 // Handle the PreRender event protectedoverridevoid OnPreRender(EventArgs e)
 {
 base.OnPreRender(e);
 CreateClientScript();
 }
 ///<SUMMARY>/// Build the markup for this custom Panel control///</SUMMARY>///<PARAMname="output"></PARAM>///<PARAMname="id"></PARAM>///<PARAMname="panelOutput"></PARAM>privatevoid BuildControlTree(HtmlTextWriter output, 
 string id, string panelOutput)
 { 
 Table t = new Table();
 //t.ID ="thePanel";  t.ID = id + "_thePanel";
 t.CellPadding = 0;
 t.CellSpacing = 0; 
 t.Width = Unit.Percentage(100); //Width; t.HorizontalAlign = HorizontalAlign.Center;
 t.Style.Add("margin", "0 0 0 0px"); 
 // Prepare the topmost row TableRow rowTop = new TableRow();
 // Leftmost cell TableCell leftCell = new TableCell(); 
 leftCell.HorizontalAlign = HorizontalAlign.Left;
 leftCell.Style.Add("width","10px"); 
 leftCell.Style.Add("background",
 tabBackColor + " url(" + imgPath + 
 "topleft.gif) top left no-repeat");
 leftCell.Text = "";
 rowTop.Cells.Add(leftCell); 
 //Label Info TableCell centerCell = new TableCell();
 centerCell.Style.Add("background-Color",tabBackColor);
 centerCell.Wrap = false;
 centerCell.Attributes.Add("onselectstart","return false"); 
 //Not allowing user to select Tab Title text //through mouse or double click.if ( hasMinimize == true )
 centerCell.Attributes.Add("ondblclick",
 String.Format("javascript:MinMaxTableCurvePanel('{0}')", id));
 Literal lit = new Literal();
 lit.Text = String.Format("{0}",Title,headerTextColor);
 centerCell.Controls.Add(lit); 
 rowTop.Cells.Add(centerCell);
 //Print Icon Cellif ( hasPrint )
 {
 TableCell printCell = new TableCell();
 //printCell.HorizontalAlign = HorizontalAlign.Right; printCell.Style.Add("background-Color",tabBackColor);
 printCell.Wrap = false;
 printCell.Width = Unit.Pixel(20);
 System.Web.UI.WebControls.Image imgPrint = 
 new System.Web.UI.WebControls.Image();
 imgPrint.AlternateText = "Print View";
 imgPrint.BorderWidth = 0;
 imgPrint.Style.Add("cursor","hand");
 imgPrint.Attributes.Add("onclick",
 String.Format("javascript:PrintTableCurvePanel('{0}')",id));
 imgPrint.ImageAlign = ImageAlign.AbsMiddle;
 imgPrint.ImageUrl = imgPath + "print.gif";
 printCell.Controls.Add(imgPrint);
 rowTop.Cells.Add(printCell);
 }
 //Minimize/Maximize Icon Cellif ( hasMinimize )
 {
 TableCell minimizeCell = new TableCell();
 //minimizeCell.HorizontalAlign = HorizontalAlign.Right; minimizeCell.Style.Add("background-Color",tabBackColor);
 minimizeCell.Wrap = false;
 minimizeCell.Width = Unit.Pixel(20);
 System.Web.UI.WebControls.Image imgMinimize = 
 new System.Web.UI.WebControls.Image();
 //imgMinimize.ID ="img"; imgMinimize.ID = id + "_imgPlusMinus";
 imgMinimize.AlternateText = "Minimize/Maximize the Panel";
 imgMinimize.BorderWidth = 0;
 imgMinimize.Style.Add("cursor","hand");
 imgMinimize.Attributes.Add("onclick",
 String.Format("javascript:MinMaxTableCurvePanel('{0}')",id));
 imgMinimize.ImageAlign = ImageAlign.AbsMiddle;
 imgMinimize.ImageUrl = 
 imgPath + (Closed==true?"plus.gif":"minus.gif");
 minimizeCell.Controls.Add(imgMinimize);
 rowTop.Cells.Add(minimizeCell);
 }
 // Right most cell TableCell rightCell = new TableCell(); 
 rightCell.HorizontalAlign = HorizontalAlign.Right;
 rightCell.Width = Unit.Pixel(10);
 rightCell.Style.Add("width","10px"); 
 rightCell.Style.Add("background",tabBackColor + 
 " url(" + imgPath + "topright.gif) top right no-repeat");
 rightCell.Text = ""; 
 rowTop.Cells.Add(rightCell);
 // Add the top row to the table t.Rows.Add(rowTop);
 int colspan = 3;
 if ( hasPrint )
 colspan++;
 if ( hasMinimize )
 colspan++;
 // Insert the Panel's markup in the table cell {Container} TableRow rowBody = new TableRow();
 if ( bodyBackColor!= Color.Transparent )
 rowBody.BackColor = bodyBackColor;
 TableCell cellBody = new TableCell(); 
 cellBody.ColumnSpan = colspan;
 cellBody.Text = panelOutput;
 cellBody.Style.Add("BORDER","#cccccc 1px solid");
 cellBody.Style.Add("padding","0 0 0 0px"); //"0 5 5 5px" cellBody.Style.Add("margin","0 0 0 0px"); //"0 0 5 0px" rowBody.Cells.Add(cellBody);
 t.Rows.Add(rowBody);
 // Output t.RenderControl(output);
 } 
 ///<SUMMARY>/// Add client side scripting///</SUMMARY>privatevoid CreateClientScript()
 {
 string jscript = @" <style> 
 P.PanelCurveTitleStyle
 {
 font-family:verdana;
 font-size: 12px;
 font-weight : bold;
 text-align: center; 
 }
 </STYLE> 
 <script language="javascript">
 var imgPath='" + imgPath + @"'; 
 </script>
 <script language="javascript"> 
 function MinMaxTableCurvePanel(cntrlId)
 {
//Get state from hidden control.
 var closed_TableCurvePanel = 
 document.getElementById(cntrlId+'_hdnMinimizeState').value;
 if ( closed_TableCurvePanel.toLowerCase() == 'true' )
 {
 document.getElementById(cntrlId).style.display = '';
 document.getElementById(cntrlId+'_hdnMinimizeState').value=
 false;
 document.getElementById(cntrlId+'_imgPlusMinus').src = 
 imgPath + 'minus.gif';
 }
 else 
 {
 document.getElementById(cntrlId).style.display = 'none';
 document.getElementById(cntrlId+'_hdnMinimizeState').value = 
 true;
 document.getElementById(cntrlId+'_imgPlusMinus').src = 
 imgPath + 'plus.gif';
 }
 }
//TODO: this could be improved further to show tab on new window.
 function PrintTableCurvePanel(cntrlId)
 { 
 var objDiv = document.getElementById(cntrlId);
 var winTableCurvePanel = 
 window.open('','winTableCurvePanelId','');
 winTableCurvePanel.document.write('
 <html><head></head><body onload=
 'javascript:window.print()'>');
 winTableCurvePanel.document.write(objDiv.innerHTML);
 winTableCurvePanel.document.write('</body></html>');
 winTableCurvePanel.focus();
 }
 </script>
";
 if (!Page.IsClientScriptBlockRegistered("TableCurvePanel_Script"))
 Page.RegisterClientScriptBlock("TableCurvePanel_Script", 
 jscript );
 }
 ///<SUMMARY>/// Render the panel in a box (MSDN like)///</SUMMARY>///<PARAMname="output"></PARAM>privatevoid RenderContentsInBox(HtmlTextWriter output)
 {
 this.Style.Add("BORDER","#cccccc 1px solid");
 this.Style.Add("padding","0 0 0 0px"); //"0 5 5 5px"this.Style.Add("margin","0 0 0 0px"); //"0 0 5 0px"base.Render(output);
 }
 }
 #endregion}

显示在顶部的图像的ASPX代码:

<%@Pagelanguage="c#"Codebehind="WebForm1.aspx.cs"AutoEventWireup="false"Inherits="PanelCurveContainer.WebForm1"%><%@RegisterTagPrefix="Tittle"namespace="Tittle.Controls"Assembly="ClassLibrary1"%><%@RegisterTagPrefix="Tittle"TagName=
"WebUserControl"Src="WebUserControl1.ascx"%><!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.0Transitional//EN"><html><head><title>WebForm1</title></head><bodyMS_POSITIONING="GridLayout"><formid="Form1"method="post"runat="server"><Tittle:PanelCurveControlID="Panelcurvecontrol1"runat="server"Expandable="true"Margin="10"Title="Panel Curve - Custom Tab Color"TabBackColor="#FF9933"> 
 <tablewidth=90% align=center><tr><td><fontsize=-1>Name:</font> 
 <asp:textboxid="Textbox1"runat="server"/></td><td><fontsize=-1>Age:</font> 
 <inputtype=text /></td></tr></table></font></Tittle:PanelCurveControl><br><Tittle:PanelCurveControlID="Panelcurvecontrol2"runat="server"Expandable="true"Title="Panel Curve - Custom Header Text Color and Content Back Color"BodyBackColor="Pink"HeaderTextColor="#009900"> Content here
 </Tittle:PanelCurveControl><br> 
 <tablewidth="95%"border=0 align=center><tr><tdvalign=top><Tittle:PanelCurveControlID="Panelcurvecontrol3"runat="server"Expandable="true"Title="Panel Curve - Without Print Icon"HasPrint="False"BodyBackColor="#CCFFFF"> Name:<br><asp:textboxid=txt runat="server"/> 
 </Tittle:PanelCurveControl><br><Tittle:PanelCurveControlID="Panelcurvecontrol4"runat="server"Expandable="true"Title="Panel Curve - Without Any Icon"HasPrint="False"HasMinimize="false"HeaderTextColor="#009900"TabBackColor="#FFCC99"> Content here
 </Tittle:PanelCurveControl></td><tdvalign=top><Tittle:PanelCurveControlID="Panelcurvecontrol5"runat="server"Expandable="true"Title="Panel Curve - Master Curve"HasMinimize="false"HasPrint="false"HeaderTextColor="pink"TabBackColor="green"> More Panels
 <tablewidth="100%"><tr> 
 <tdvalign=top ><Tittle:PanelCurveControlID="Panelcurvecontrol7"runat="server"Expandable="true"Title="Panel Curve - Master Curve - Child 1"HasMinimize="false"HasPrint="false"HeaderTextColor="#666600"TabBackColor="#CCFFCC"> One More Child
 <Tittle:PanelCurveControlID="Panelcurvecontrol8"runat="server"Expandable="true"Title="Panel Curve - Master Curve - Child 1 - Child 1"HasPrint="false"HeaderTextColor="white"TabBackColor="#336699"> Content here 
 </Tittle:PanelCurveControl></Tittle:PanelCurveControl></td></tr></table></Tittle:PanelCurveControl></td></tr></table> 
 <tittle:WebUserControlid="WebUserControl1"runat="server"/><br><br><br></form></body></html>

结束语

我真的很感兴趣知道这个代码是否有帮助,请不要犹豫或者懒惰地告诉你提交的内容。 如果你在控制代码中保留这个页面的URL,我会感到非常感谢。

历史记录

  • 创建于:15 2005年月。

控制  asp  asp-net  Contain  PAN  PANE