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;
}

Leave a comment