Bubbling Windows Forms Events With Anonymous Methods

The following code illustrates a great use for anonymous methods.

public class MyContainerControl : Control
{
private class MySpecializedControl : Control
{
protected virtual void OnMyEvent(EventArgs e)
{
if (this.MyEvent != null)
this.MyEvent(this, e);
}
public event EventHandler MyEvent;
}
private MySpecializedControl special;
public MyContainerControl()
{
this.special = new MySpecializedControl();
// ...
this.Controls.Add(this.special);
this.special.MyEvent += delegate(object sender, EventArgs e) { this.OnMyEvent(e); };
}
protected virtual void OnMyEvent(EventArgs e)
{
if (this.MyEvent != null)
this.MyEvent(this, e);
}
public event EventHandler MyEvent;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s