【散300分】我刚刚“不小心”回复了一个行为模式的例子,推荐给大家参考
我给你举一个“更好地封装”的例子。作为架构师大多数时候整天都是研究开发组件的,只有那些小程序员整天copy代码。这里,我们抽象出“行为(beheavior)”来,你不是要将某个asp.net组件添加click事件吗?好吧,将这个行为封装到一个ascx中去!
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
using System;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;public partial class WebUserControl : System.Web.UI.UserControl, IPostBackEventHandler{ public string TargetID { get; set; } public event EventHandler<EventArgs> Click; public void RaisePostBackEvent(string eventArgument) { if (this.Click != null) this.Click(this, EventArgs.Empty); } protected void Page_PreRender(object sender, EventArgs e) { var ctl = this.Parent.FindControl(this.TargetID); var script = this.Page.ClientScript.GetPostBackEventReference(this, string.Empty); if (ctl is HtmlControl) ((HtmlContainerControl)ctl).Attributes["onclick"] = script; else if (ctl is WebControl) ((WebControl)ctl).Attributes["onclick"] = script; else if(ctl is WebUserControl) ((WebUserControl)ctl).Attributes["onclick"] = script; }}
:<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><%@ Register Src="WebUserControl.ascx" TagName="WebUserControl" TagPrefix="uc1" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title></title></head><body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"> <ContentTemplate> <div runat="server" id="myDiv"> click me </div> <uc1:WebUserControl ID="WebUserControl1" runat="server" TargetID="myDiv" OnClick="myDiv_Clicked" /> </ContentTemplate> </asp:UpdatePanel> </form></body></html>
using System;using System.Web.UI;public partial class _Default : System.Web.UI.Page{ protected void myDiv_Clicked(object sender, EventArgs e) { ScriptManager.RegisterStartupScript(this, this.GetType(), this.GetHashCode().ToString(), "alert('点击了myDiv');", true); }}
[解决办法]
学习,JF,先谢谢LZ分享
[解决办法]
学习
[解决办法]
接分,难得看到sp1234大师散分
[解决办法]
每天回帖即可获得10分可用分!
[解决办法]