How to expose events in a WinForms custom control
I've developed a custom control that acts like a group box with a check box over the group label. The idea being, once the check box is unchecked all the controls in the group are disabled.
I need to expose the Check changed event so that external actions could be performed if required. I've also exposed the Check state changed.
Currently, when the control is used it changes the check state when any of the controls in the group loose focus.
When I handle the check changed event, should I then re-fire the event for any external handlers?
The events defined:
/// <summary>
/// Event to forward the change in checked flag
/// </summary>
public event EventHandler CheckedChanged;
/// <summary>
/// Event to forward the change in checked state of the checkbox
/// </summary>
public event EventHandler CheckStateChanged;
The event handler code:
private void chkBox_CheckedChanged(object sender, EventArgs e)
{
// Disable the controls within the group
foreach( Control ctrl in this.Controls )
{
if( ctrl.Name != "chkBox" && ctrl.Name != "lb开发者_StackOverflow社区lDisplay" )
{
ctrl.Enabled = this.chkBox.Checked;
}
}
// Now forward the Event from the checkbox
if (this.CheckedChanged != null)
{
this.CheckedChanged(sender, e);
}
}
private void chkBox_CheckStateChanged(object sender, EventArgs e)
{
// Forward the Event from the checkbox
if( this.CheckStateChanged != null )
{
this.CheckStateChanged( sender, e );
}
}
You are almost there. You just have to register your event with a event handler in external class.
CheckedChanged += ExternalChkBox_CheckChanged;
private void ExternalChkBox_CheckChanged(object sender, EventArgs e)
{
// External trigger
}
精彩评论