清理这种模式的方法?使用私有布尔标志来表示用户何时更改 UI 与何时 class 更改 UI?

Way to clean up this pattern? Using private bool flag to denote when user changes UI vs when the class changes UI?

我发现自己经常使用这种模式

private boolean cbDeviceIndexInternal = false;
private void cbDevices_SelectedIndexChanged(object sender, EventArgs e)
{
    if (!cbDeviceIndexInternal)
        DeviceChanged();
    cbDeviceIndexInternal = false;
}
...
cbDeviceIndexInternal = true;
cbDevices.SelectedIndex = 0;

作为 SelectedIndex 被更改的结果,无论索引是由用户更改还是由 class 本身更改,都会引发一个事件。我真的很讨厌使用这段代码,但它是我找到的最好的解决方案。

有没有人遇到过这个,你是怎么解决的?

您不一定要添加 删除处理程序。只是在 Load 事件结束之前不要添加处理程序。这样,当您对控件进行编程更改时,它们就不会出现和触发。