Ahm*_*eed 24 .net c# event-handling checkedlistbox winforms
CheckedListBox
使用鼠标单击时,WinForms 控件有2个默认行为:
作为一项便利功能,我需要允许用户一键切换选择.我已经实现了这一点,所以现在只需点击一下即可实现上面的默认行为#1.问题是当单击相同(即当前选定的)项目时,行为#2不再正常工作.它在项目之间跳转时工作正常,这是理想的,但同一项目最多需要4次点击.
我的解决方法是,如果用户重复选择相同的项目,则调用两次切换逻辑.关于我的问题:
奇怪的是,调试代码显示已检查状态已更改但在UI方面没有出现,直到它被调用两次.我认为它可能与线程相关,但它不是一个可能需要BeginInvoke
使用的可重入事件.
这是我的代码:
using System.Linq;
using System.Windows.Forms;
namespace ToggleCheckedListBoxSelection
{
public partial class Form1 : Form
{
// default value of -1 since first item index is always 0
private int lastIndex = -1;
public Form1()
{
InitializeComponent();
CheckedListBox clb = new CheckedListBox();
clb.Items.AddRange(Enumerable.Range(1, 10).Cast<object>().ToArray());
clb.MouseClick += clb_MouseClick;
this.Controls.Add(clb);
}
private void clb_MouseClick(object sender, MouseEventArgs e)
{
var clb = (CheckedListBox)sender;
Toggle(clb);
// call toggle method again if user is trying to toggle the same item they were last on
// this solves the issue where calling it once leaves it unchecked
// comment these 2 lines out to reproduce issue (use a single click, not a double click)
if (lastIndex == clb.SelectedIndex)
Toggle(clb);
lastIndex = clb.SelectedIndex;
}
private void Toggle(CheckedListBox clb)
{
clb.SetItemChecked(clb.SelectedIndex, !clb.GetItemChecked(clb.SelectedIndex));
}
}
}
Run Code Online (Sandbox Code Playgroud)
要重现我的问题,请注释代码注释中提到的行,并按照以下步骤操作:
谢谢阅读!
Jef*_*ata 49
作为一项便利功能,我需要允许用户一键切换选择.
我不知道做什么用的代码发生,但设置CheckOnClick到true
会做到这一点:
CheckOnClick指示每当选择项目时是否应切换复选框.默认行为是在第一次单击时更改选择,然后让用户再次单击以应用复选标记.但是,在某些情况下,您可能希望在单击项目后立即检查该项目.
归档时间: |
|
查看次数: |
8977 次 |
最近记录: |