编辑:
包含此控件的页面必须处理此事件。
我该如何做?
首先,您需要在UserControl
上定义一个事件,允许包含UserControl
的Page
注册和处理该事件。例如:
public partial class MyUserControl : System.Web.UI.UserControl
{
// Event for page to handle
public event EventHandler DivClicked;
protected virtual void OnDivClicked(EventArgs e)
{
if (DivClicked != null)
DivClicked(this, e);
}
protected void Page_Load(object sender, EventArgs e)
{
// Page Load Code goes here
}
}
现在,通过将onclick
属性添加到div
,每次单击时都会向服务器提交。因此,当后台回发导致调用Page_Load
时,我检查它是否是由div
引起的回发。如果是,我会触发UserControl
的DivClicked
事件,由页面处理。
public partial class MyUserControl : System.Web.UI.UserControl
{
// Event Definition and Raising methods
...
protected void Page_Load(object sender, EventArgs e)
{
// @@@@ will denote this is an argument I provided.
string arg = "@@@@" + divClickableDiv.ClientID;
// Add postback method to onClick
divClickableDiv.Attributes.Add("onClick",
Page.ClientScript.GetPostBackEventReference(divClickableDiv, arg));
if (IsPostBack)
{
// Get event arguments for post back.
string eventArg = Request["__EVENTARGUMENT"];
// Determine if postback is a custom postback added by me.
if (!string.IsNullOrEmpty(eventArg) && eventArg.StartsWith("@@@@"))
{
// Raise the click event for this UserControl if the div
// caused the post back.
if (eventArg == arg)
OnDivClicked(EventArgs.Empty);
}
}
}
}
这样就完成了 UserControl
的编写,现在你只需要在页面上注册 DivClicked
事件即可。
不幸的是,你无法在设计时支持中注册该事件。但是,你仍然可以将代码添加到 .aspx 页面中。在放置 UserControl
的页面上,向 UserControl
添加一个名为 OnXXX
的属性,其中 XXX 是事件名称。因此,对于我上面的示例,我在页面上定义 UserControl
如下:
<uc1:MyUserControl ID="MyUserControl1" runat="server" OnDivClicked="MyUserControl1_DivClicked" />
public partial class MyPage : System.Web.UI.Page
{
// Called whenever div in MyUserControl is clicked.
protected void WebUserControl1_DivClicked(object sender, EventArgs e)
{
// Handle Div click event here.
}
}
应该就这样了。希望这篇文章能帮到你。
<div runat="server" onserverclick="MyClickHandler">
...
</div>
Rocka的回答接近正确,但并不完全正确(因为它对我没有用,我找出了原因)。
Rocka用户控件的代码片段是正确的: // 由页面处理的事件 public event EventHandler DivClicked;
protected virtual void OnDivClicked(EventArgs e)
{
if (DivClicked != null)
DivClicked(this, e);
}
当使用UserControl时,以下内容将不起作用:
OnDivClicked不是事件处理程序,而是一个函数,因此您无法分配它。更何况,当函数触发时,实际的事件处理程序变量为null,因此不会执行任何操作。
正确的方法应该是:
这将把MyUserControl1_DivClicked分配为DivClicked的处理程序。可惜,这实际上并没有起作用,所以在页面的Page_Load中的代码后端中,改为使用以下行:
this.MyUserControl1.OnClick += new EventHandler(MyUserControl1);
另外,顺便提一下,如果将div设置为runat="server",则OnClick将公开为可以连接到的事件。您所需要的就是在用户控件中为EventHandler添加一个传递属性到div。
<asp:Panel ID="ImgFeatured" runat="server" CssClass="featured-ribbon"> </asp:Panel>
代码后台
Panel ImgFeatured = (Panel)e.Row.FindControl("ImgFeatured");
ImgFeatured.Visible = true;