Exposing Child Control Events In A User Control

Sometimes we want to add handlers to events raised by children of a User Control. As far as I could google these are your options.

1. The  simplest way is to provide an accessor method that returns the control. Chances are if you only expose certain properties of your child control, developers will want access to some other property so just put it all out there:

public Button ChildButton
{
    get { return btnChild; }
}

Now you can add handlers to the click event like so:

myUserControl.ChildButton.OnClick += MyClickHandler;

2. If you really want to restrict the developer to using a particular event, you can create a new public event which is fired by the event handler of the child control:

public event EventHandler ChildButtonClicked;

...

private void btnChild_OnClick(object sender, EventArgs e)
{
    if(ChildButtonClicked != null)
        ChildButtonClicked(this, e);
}

Happy exposing!

Jimmy

Related posts

Comments

Add comment


 

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

September 9. 2010 09:34

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010