当使用鼠标单击时,WinForms CheckedListBox控件有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));
}
}
}要重现我的问题注释,将代码注释中提到的行注释掉,并遵循以下步骤:
感谢您的阅读!
发布于 2010-11-03 03:22:52
作为一个方便的特性,我需要允许用户在一次单击中切换所选内容。
我不确定代码发生了什么变化,但是将CheckOnClick设置为true可以做到这一点:
CheckOnClick指示每当选中某项时是否应切换复选框。默认行为是在第一次单击时更改所选内容,然后让用户再次单击以应用复选标记。但是,在某些情况下,您可能希望单击该项目后立即进行检查。
https://stackoverflow.com/questions/4083703
复制相似问题