【发布时间】:2012-05-01 23:24:34
【问题描述】:
我有一个母版页和一个 aspx 页面。 我希望他们每个人都侦听从内部用户控件(即不在页面本身中,而是在另一个用户控件中的用户控件)调度的事件?
角色转换会更容易吗?意味着内部控件将通知它的母版页? 我看到了这个: Help with c# event listening and usercontrols
但我认为我的问题更复杂。
【问题讨论】:
标签: c# asp.net event-handling
我有一个母版页和一个 aspx 页面。 我希望他们每个人都侦听从内部用户控件(即不在页面本身中,而是在另一个用户控件中的用户控件)调度的事件?
角色转换会更容易吗?意味着内部控件将通知它的母版页? 我看到了这个: Help with c# event listening and usercontrols
但我认为我的问题更复杂。
【问题讨论】:
标签: c# asp.net event-handling
您可以沿着页面的路线通过它们的控件递归找到 UserControl 并附加到它的 EventHandler 上,这是最简单和最直接的方式。
这需要更多的工作,但我喜欢单个事件总线的想法,您的页面可以使用它来注册为特定事件的观察者(无论是谁发送它)。然后,您的 UserControl 也可以通过它发布事件。这意味着链的两端只依赖于事件(和总线,或一个接口),而不是特定的发布者/订阅者。
您需要注意线程安全并确保您的控件正确共享事件总线。我相信ASP.NET WebForms MVP 项目采用了这种方法,你可以看看。
【讨论】:
尝试使用以下方法:
在您的用户控件中定义一个事件
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;
}
希望这会有所帮助。
【讨论】: