Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to expose events of a member object of a class to the outside in .NET?

Tags:

c#

.net

events

Say I have a User Control in ASP.NET that contains a button:

public class MyUserControl : UserControl {
    private Button btnSave = new Button();
}

I can expose any property of the button to the outside by making a property that points at the button:

public string SaveButtonText { 
    get { return btnSave.Text; } 
    set { btnSave.Text = value; } 
}

So then I can do this to set the button's text:

MyControl.SaveButtonText = "hello world";

Is there a similar construct I can use to expose the button's events to the outside as well? Something like:

public event SaveButtonClick { return btnSave.OnClick; }
...
MyControl.SaveButtonClick += new EventHandler(...);
like image 395
MisterZimbu Avatar asked Aug 31 '10 18:08

MisterZimbu


Video Answer


2 Answers

You can do something like that, yes:

public event EventHandler SaveButtonClick
{
    add { btnSave.Click += value; }
    remove { btnSave.Click -= value; }
}

Note however that there's one downside to this - the "sender" argument supplied to the event handlers will still be the save button rather than your control... that may not be what the subscriber expected. An alternative approach is to subscribe once to the save button's click handler yourself:

public event EventHandler SaveButtonClick = delegate {};

private void OnSaveButtonClicked(object sender, EventArgs e)
{
    // Replace the original sender with "this"
    SaveButtonClick(this, e);
}
...
btnSave.Click += OnSaveButtonClicked();

There's a downside to this approach too... you end up having a reference from the save button to "this" all the time, which may have an impact on garbage collection. Basically your control won't be able to be garbage collected until the save button is also eligible for garbage collection. In this case I very much doubt that it's an issue, but it's worth being aware of.

like image 134
Jon Skeet Avatar answered Sep 23 '22 19:09

Jon Skeet


    public event EventHandler SaveButtonClick {
        add { btnSave.Click += new EventHandler (value); }
        remove { btnSave.Click-= new EventHandler (value); }
    }
like image 20
Jeff Avatar answered Sep 23 '22 19:09

Jeff