[英]C# .net bubble down an event from Page to usercontrol (child)
用户控件(子级,stuff.ascx)页面可以对页面(父级,page.aspx)中的事件做出反应吗? 我在父页面上有一个按钮。 Onclick我想向孩子触发一个事件。
doesStuff.ascx:
//这样的东西
((doesStuff)this.Page).someButtonControl.click;
// 要么
something.Click += new EventHandler(someReference???);
如果我真正了解您,则可以为此目的使用委托。 在用户控件uc1中:
public Action action;
protected void btnSubmit_Click(object sender, EventArgs e)
{
action();
}
并在页面中:
protected void Page_Load(object sender, EventArgs e)
{
uc1.action = someAction;
}
public void someAction()
{
//Do Some thing
}
如果要将参数从子控件传递给父控件,则可以使用CommandEventHandler 。
<%@ Register Src="~/DoesStuff.ascx" TagPrefix="uc1" TagName="DoesStuff" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<form id="form1" runat="server">
<uc1:DoesStuff runat="server" ID="DoesStuff"
OnChildButtonClicked="DoesStuff_ChildButtonClicked" />
</form>
</body>
</html>
public partial class Parent : System.Web.UI.Page
{
protected void DoesStuff_ChildButtonClicked(object sender, EventArgs e) { }
}
<asp:Button ID="BubbleUpButton" runat="server"
Text="Bubble Up to Parent"
OnClick="BubbleUpButton_OnClick" />
public partial class DoesStuff : System.Web.UI.UserControl
{
public event EventHandler ChildButtonClicked = delegate { };
protected void BubbleUpButton_OnClick(object sender, EventArgs e)
{
// bubble up the event to parent.
ChildButtonClicked(this, new EventArgs());
}
}
在ASP.Net Web窗体中 ,没有基础控件就将一个事件调用到另一个事件不是一个好习惯。
相反,您想创建一个公共方法,并从Parent调用它。 例如,
// Parent
public partial class Parent : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var doesStuff = DoesStuff1 as DoesStuff;
if (doesStuff != null) DoesStuff1.DisplayMessage("Hello from Parent!");
}
}
// Child
public partial class DoesStuff : System.Web.UI.UserControl
{
public void DisplayMessage(string message)
{
ChildLabel.Text = message;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.