Only change a ListViewItem's Checked state if the checkbox is clicked

那年仲夏 提交于 2019-12-10 17:05:34

问题


By default, double-clicking a ListViewItem toggles its Checked state. I only want the Checked state to be changed by clicking an the item's checkbox or pressing the space bar while an item is highlighted. Is this easy to do?


回答1:


The solution involves 3 events and one state variable of type bool:

private bool inhibitAutoCheck;

private void listView1_MouseDown(object sender, MouseEventArgs e) {
    inhibitAutoCheck = true;
}

private void listView1_MouseUp(object sender, MouseEventArgs e) {
    inhibitAutoCheck = false;
}

private void listView1_ItemCheck(object sender, ItemCheckEventArgs e) {
    if (inhibitAutoCheck)
        e.NewValue = e.CurrentValue;
}

The item check enables to avoid the transition to another check state (called before the ItemChecked event). The solution is simple and sure.

To find it out I made a small test with different events:

When clicking:

  1. MouseDown <------------- inhibited region
  2. Click
  3. MouseClick
  4. MouseUp ------------->
  5. ItemCheck (outside inhibited region)
  6. ItemChecked

When double clicking:

  1. MouseDown <------------- inhibited region
  2. ItemSelectionChanged
  3. SelectedIndexChanged
  4. Click
  5. MouseClick
  6. MouseUp ------------->
  7. MouseDown <------------- inhibited region
  8. ItemCheck (inside inhibited region)
  9. ItemActivate
  10. DoubleClick
  11. MouseDoubleClick
  12. MouseUp ------------->


来源:https://stackoverflow.com/questions/1406887/only-change-a-listviewitems-checked-state-if-the-checkbox-is-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!