Event triggering without a direct connection?
In my ASP.NET app I have a control in the ma开发者_JAVA百科ster page that raises an event Foo
on certain occasions / interactions.
I also have a couple of pages that have another control that must re-bind itself when this event is fired.
Unfortunately the only way I can see them communicating between each other is by creating a long event chain (deriving a new MasterPage MasterPageSuperDuper
, attaching an event handler to Foo
's event in the user control, and then referring to this event in the masterpage from the control present in a couple of pages - basically using the masterpage as a control center).
Is it possible to raise an event the page control can see without getting the masterpage involved?
Here we go.
Create an Interface, put in app_code folder
public interface IBinder
{
void Bind();
}
PageControl Implement Interface
public partial class WebUserControl2 : System.Web.UI.UserControl, IBinder
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void Bind()
{
}
}
In your Control on the masterpage
public partial class WebUserControl1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void butRaiseEvent_Click(object sender, EventArgs e)
{
CheckSub(this.Parent.Parent.Controls);
}
private void CheckSub(ControlCollection cc)
{
foreach (Control c in cc)
{
if (c is IBinder)
((IBinder)c).Bind();
else
CheckSub(c.Controls);
}
}
}
Let me know if it works.
The controls on the page have no clue who the other "children" are, so you can't automagically have them say "look, there is another control on this page. How are you doing other control?" without doing some work, normally through the parent container.
There are mechanisms you can use to kludge things, but you still have to get the events through a common "container" like the page or master page.
I am curious why you are raising events in your master page that require such intricate control at the child level. I would imagine there is a more elegant architectural solution.
精彩评论