[英]How can a master page/aspx page listen to an event that is dispatched in a usercontrol inside another usercontrol
我有一个母版页和一个aspx页。 我希望他们每个人都听从内部用户控件(即不在页面本身中,而是在另一个用户控件中的用户控件)调度的事件吗?
切换角色会更容易吗? 意味着内部控件将通知它的母版页? 我看到了这一点: 有关c#事件侦听和用户控件的帮助
但是我的问题更复杂。
尝试使用以下方法:
在您的UserControl中定义一个事件
public delegate void UserControl2Delegate(object sender, EventArgs e);
public partial class UserControl2 : System.Web.UI.UserControl
{
public event UserControl2Delegate UserControl2Event;
//Button click to invoke the event
protected void Button_Click(object sender, EventArgs e)
{
if (UserControl2Event != null)
{
UserControl2Event(this, new EventArgs());
}
}
}
通过递归控件集合并附加事件处理程序,在页面/主加载方法中找到UserControl
UserControl2 userControl2 = (UserControl2)FindControl(this, "UserControl2");
userControl2.UserControl2Event += new UserControl2Delegate(userControl2_UserControl2Event);
...
void userControl2_UserControl2Event(object sender, EventArgs e)
{
//Do something
}
...
private Control FindControl(Control parent, string id)
{
foreach (Control child in parent.Controls)
{
string childId = string.Empty;
if (child.ID != null)
{
childId = child.ID;
}
if (childId.ToLower() == id.ToLower())
{
return child;
}
else
{
if (child.HasControls())
{
Control response = FindControl(child, id);
if (response != null)
return response;
}
}
}
return null;
}
希望这可以帮助。
您可以沿着页面的路径浏览它们的控件,以找到UserControl并将其附加到EventHandler上,这是最简单,最直接的方法。
这还需要做更多的工作,但是我喜欢单个事件总线的想法,您的页面可以使用该事件总线注册为特定事件的观察者(无论是谁发送的)。 然后,您的UserControl也可以通过此控件发布事件。 这意味着链的两端仅取决于事件(和总线,或一个接口),而不是特定的发布者/订阅者。
您需要注意线程安全性,并确保您的控件正确共享事件总线。 我相信ASP.NET WebForms MVP项目采用了您可以研究的这种方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.