gpt4 book ai didi

c# - ItemChecked 事件处理程序

转载 作者:行者123 更新时间:2023-12-02 22:41:45 25 4
gpt4 key购买 nike

我使用以下代码将 CheckedListBox 中选中的项目数限制为 1:

        private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (checkedListBox1.CheckedItems.Count == 1)
{
Boolean isCheckedItemBeingUnchecked = (e.CurrentValue == CheckState.Checked);
if (isCheckedItemBeingUnchecked)
{
e.NewValue = CheckState.Checked;
}
else
{
Int32 checkedItemIndex = checkedListBox1.CheckedIndices[0];
checkedListBox1.ItemCheck -= checkedListBox1_ItemCheck;
checkedListBox1.SetItemChecked(checkedItemIndex, false);
checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
}
return;
}
}

但有些时候我需要清除所有勾选的项目。我正在使用下面的代码来尝试这样做,但之前的事件阻止了它的工作。我怎样才能做到这一点?谢谢。

    public void ClearChecked()
{
foreach (int checkedItemIndex in checkedListBox1.CheckedIndices)
{
checkedListBox1.SetItemChecked(checkedItemIndex, false);
}
}

最佳答案

您可以创建一个新变量来指示何时应忽略 ItemCheck 事件:

private shouldIgnoreCheckEvent;

public void ClearChecked()
{
this.shouldIgnoreCheckEvent = true;

foreach (int checkedItemIndex in checkedListBox1.CheckedIndices)
{
checkedListBox1.SetItemChecked(checkedItemIndex, false);
}

this.shouldIgnoreCheckEvent = false;
}

并更新您的 ItemCheck 方法以检查它是否应该被忽略:

private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (!this.shouldIgnoreCheckEvent && checkedListBox1.CheckedItems.Count == 1)
{
Boolean isCheckedItemBeingUnchecked = (e.CurrentValue == CheckState.Checked);
if (isCheckedItemBeingUnchecked)
{
e.NewValue = CheckState.Checked;
}
else
{
Int32 checkedItemIndex = checkedListBox1.CheckedIndices[0];
checkedListBox1.ItemCheck -= checkedListBox1_ItemCheck;
checkedListBox1.SetItemChecked(checkedItemIndex, false);
checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
}
return;
}
}

关于c# - ItemChecked 事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10702897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com