如何确保在事件方法内部调用之前发生 ItemCheck

How to ensure ItemCheck occurs before calls inside the event method

所以这个问题真的很简单。我有一个 checkedListBox,在 ItemCheck 上我想调用我的方法 UpdateGraph()。问题是,如果我在事件中调用它,它会在项目被视为检查之前通过 UpdateGraph 方法运行。由于更新图方法使用 foreach(checkListBox.CheckedItems 中的 var 项目) checked or not 的新值已经应用很重要。

我通过在事件中手动设置新值尝试了一种解决方法,但是,这给了我一个 WhosebugException。

private void checkedListBox3_ItemCheck(object sender, ItemCheckEventArgs e)
{

    if (e.NewValue == CheckState.Checked)
    {
        checkedListBox3.SetItemChecked(e.Index, true);
    }
    else
    {
        checkedListBox3.SetItemChecked(e.Index, false);
    }

    UpdateChart();
}

它给了我 SetItemChecked 所在行的异常。 重申一下,我希望在 UpdateChart() 之前检查该项目,而仅调用 UpdateChart() 似乎并不能做到这一点。在项目进入 UpdateChart() 方法之前,是否有人有任何解决方法来检查项目?

编辑:谢谢,我现在明白为什么我现在得到 WhosebugException,但是是否有办法确保项目采用新的 CheckState 而无需手动将其传递到我的 UpdateGraph 方法?它是一种通用方法,不会总是通过我的 checkedListBox3_itemCheck 事件,因此传入 newCheckstate 可能会使事情复杂化。请注意,我可以只使用 If 来检查我传入的值并使用某种标识符来确定是否需要使用它,但是如果我在进入之前找不到其他任何东西来更新检查状态,那可能是我最后的解决方案方法。

正如您所指出的,在设置值后没有发生 OnItemChecked 事件,因此您必须考虑另一种方式:

您可以将您的更新方法重构为类似 UpdateGraph(int? changedIndex = null, bool isChecked = false) 这样的方式,您可以像 UpdateGraph() 当前使用它的地方那样调用它,然后

private void checkedListBox3_ItemCheck(object sender, ItemCheckEventArgs e)
{
    UpdateGraph(e.Index, e.NewValue == CheckState.Checked);
}

在正常评估您的 foreach 之后,您可以检查 changedIndex == null 并做出相应的反应。