How can a master page/aspx page listen to an event that is dispatched in a usercontrol inside another usercontrol
I have a master page and an aspx page. I want each of them to listen to an event that is dispatched from a inner user control (meaning a user-control which is not in the page itself, but inside another user-control) ?
Would it be easier to switch roles? meaning the inner control will notify it's master page ? I saw this: Help with c# event listening and usercontrols
but my problem is more complicated I think.
You could go down the route of the pages recursing through their controls to find the UserControl and attach to the EventHandler of it which is the simplest and most straight-forward way.
It's a bit more work, but I like the idea of a single Event Bus that your pages can use to register as observers of a particular event (regardless of who sends it). Your UserControl can then also publish the events through this. This means that both ends of the chain are just dependent on the event (and the bus, or an interface of one), rather than a specific publisher / subscriber.
You would need to be careful with thread-safety and making sure your controls share the Event Bus correctly. I believe the ASP.NET WebForms MVP project takes this approach which you could look at.
Try using the following approach:
Define an event in your 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());
}
}
}
Find the UserControl in your Page/Master Load methods by recursing the controls collection and attaching an event handler
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;
}
Hope this helps.
精彩评论