Is it possible to expose events of a member object of a class to the outside in .NET?
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 makin开发者_开发技巧g 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(...);
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.
public event EventHandler SaveButtonClick {
add { btnSave.Click += new EventHandler (value); }
remove { btnSave.Click-= new EventHandler (value); }
}
精彩评论