2013-08-20 156 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 { 
    //.... 
    } 
}