2013-08-20 241 views
2

我有一個表單,其中包含兩個元素:一個CheckedListBox和一個CheckBoxCheckBox稱爲SelectAllCheckBox,用於檢查/取消選中CheckedListBox中的所有項目。我通過與SelectAllCheckBox關聯的CheckedChanged事件處理程序來實現此目的,因此在檢查時會檢查CheckedListBox中的所有項目,反之亦然。這工作正常。選擇所有複選框和CheckedListBox

我也有代碼,當用戶取消選中CheckedListBox中的某個複選框時,將取消選中SelectAllCheckBox。例如,如果用戶檢查SelectAllCheckBox,然後取消選中其中一項,則應取消選中全選CheckBox。這是通過CheckedListBox.ItemChecked事件處理程序實現的。這也很好。

我的問題是,當SelectAllCheckBox以編程方式取消選中(如上述情形)時,其事件處理程序會導致CheckedListBox中的所有項目變爲未選中狀態。

我相信別人會遇到我的問題;有沒有一個優雅的解決方法?

+0

可以請發佈一些您的代碼供我們使用? – Khan

+0

代碼將有幫助 – Ehsan

回答

2

另一種方式是利用事實上,當你以編程方式檢查/取消選中,它不會把焦點放在複選框上。因此,您可以使用Focused屬性作爲標誌。

private void SelectAllCheckBox_CheckedChanged(object sender, EventArgs e) 
{ 
    if(!((CheckBox)sender).Focused) 
     return; 
    //your code to uncheck/check all CheckedListBox here 
} 

無需創建另一個單獨的bool標誌(除非手動更改某處的焦點狀態)。

+0

聰明。這就是我正在尋找的 - 一種區分程序化和用戶檢查的方法。 –

2

你可以使用一些標誌:

bool suppressCheckedChanged; 
private void SelectAllCheckBox_CheckedChanged(object sender, EventArgs e){ 
    if(suppressCheckedChanged) return; 
    //your code here 
    //.... 
} 
//Then whenever you want to programmatically change the Checked of your SelectAllCheckBox 
//you can do something like this 
suppressCheckedChanged = true; 
SelectAllCheckBox.Checked = false; 
suppressCheckedChanged = false; 

另一種方法是你可以嘗試其他類型的事件,如ClickDoubleClick(必須同時使用):

private void SelectAllCheckBox_Click(object sender, EventArgs e){ 
    DoStuff(); 
} 
private void SelectAllCheckBox_DoubleClick(object sender, EventArgs e){ 
    DoStuff(); 
} 
private void DoStuff(){ 
    //your code here; 
    if(SelectAllCheckBox.Checked){ 
     //.... 
    } 
    else { 
    //.... 
    } 
}