- HTML code
- <%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs"
Inherits="WebUserControl" %>
- C# code
- 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 { return bb; }
set { bb = value; } }
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)
{
Control ctl = this.Parent.FindControl(this.TargetID);
string 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;
}
}
这个ascx是实现我上面说的那个接口的,也就是说它要把回发引导它自己。然后,有一个TargetID属性你 可以用于设置它要控制的组件的ID。当它工作时,它向TargetID标记出的控件注入(attach)一个客户端onclick事件,当客户在页面上点 击那个控件时,这个ascx的Click事件就被触发了!
我们还是用前面的demo,这回要写的代码简单多了,只要把这 个ascx用鼠标拖入要控制的控件的旁边放下,声明两个属性
- HTML code
- :<%@ 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>
- C# code
- 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);
}
}
如果你需要控制哪一个控件为它加上单击事件,就把这个“单击”行为工具拖到它的旁边放下,然后简单地设 置一下TargetID属性和click事件就行了。