C# 带有按钮 onClick 事件的 UserControl 的事件处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/973942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Eventhandler for UserControl with button onClick event
提问by teebot
I've created a user control that contains a button and a few other controls.
我创建了一个用户控件,其中包含一个按钮和一些其他控件。
When declaring my user control in the html markup I'd like to do some sort of :
在 html 标记中声明我的用户控件时,我想做一些事情:
<asp:CustomControl onclick="CustomControl_Click" ID="cc1" runat="server">
Where CustomControl_Click is obviously the action I want to call when my control's button is clicked.
其中 CustomControl_Click 显然是单击控件按钮时要调用的操作。
So far in my control I have:
到目前为止,在我的控制之下,我有:
public event EventHandler Click;
protected void Button1_Click(object sender, EventArgs e)
{
Click.Invoke(sender, e);
}
but how can I forwardthe Eventhandler of the parent page to assign it to the Click Eventhandler in my control?
但是如何转发父页面的 Eventhandler 以将其分配给我的控件中的 Click Eventhandler?
Any help is reallyappreciated!
任何帮助真的很感激!
PS: maybe there's a way of getting the method from the hosting page using reflexion
PS:也许有一种使用反射从托管页面获取方法的方法
采纳答案by TheVillageIdiot
I'm using a custom button (actually html div with LinkButtonembedded in it). Here is code of it:
我正在使用自定义按钮(实际上是嵌入了LinkButton 的html div )。这是它的代码:
public delegate void ClickEventHandler(object sender, EventArgs e);
public event ClickEventHandler Click = delegate { };
public string Text
{
get { return cmdLink.Text; }
set { cmdLink.Text = value; }
}
public bool CausesValidation
{
get { return cmdLink.CausesValidation; }
set { cmdLink.CausesValidation = value; }
}
public string OnClientClick
{
get { return cmdLink.OnClientClick; }
set { cmdLink.OnClientClick = value; }
}
public string CssClass
{
get { return cmdLink.CssClass; }
set { cmdLink.CssClass = value; }
}
protected void cmdLink_Click(object sender, EventArgs e)
{
Click(this, e);
}
Here is usage in aspx page:
这是aspx页面中的用法:
<Button_Control:ButtonControl ID="btnSave" runat="server" Text="Save"
OnClick="btnSaveClick" />
and this is in code-behind page of aspx page:
这是在aspx页面的代码隐藏页面中:
protected void btnSaveClick(object sender, EventArgs e)
{
//do stuff here
}
回答by teebot
I found it!
我找到了!
Instead of using event bubbling I use reflexion in the click eventhandler of the user control so I have :
我没有使用事件冒泡,而是在用户控件的单击事件处理程序中使用反射,所以我有:
public string OnClick;
protected void Button1_Click(object sender, EventArgs e)
{
MethodInfo methodInfo = this.Page.GetType().GetMethod(OnClick);
methodInfo.Invoke(this.Page, new object[]{ sender, e });
}
And it works with declaring the user control as :
它适用于将用户控件声明为:
<asp:CustomControl OnClick="CustomControl_Click" ID="cc1" runat="server">