[英]How to expose events in a WinForms custom control
我開發了一個自定義控件,其作用類似於組框,在組 label 上帶有一個復選框。 這個想法是,一旦取消選中該復選框,該組中的所有控件都將被禁用。
我需要公開 Check changed 事件,以便可以在需要時執行外部操作。 我還公開了 Check state 已更改。
目前,當使用控件時,當組中的任何控件失去焦點時,它會更改檢查 state。
當我處理檢查更改事件時,是否應該為任何外部處理程序重新觸發該事件?
定義的事件:
/// <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;
事件處理程序代碼:
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 != "lblDisplay" )
{
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 );
}
}
你快到了。 您只需使用外部 class 中的事件處理程序注冊您的事件。
CheckedChanged += ExternalChkBox_CheckChanged;
private void ExternalChkBox_CheckChanged(object sender, EventArgs e)
{
// External trigger
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.