Windows窗体如何确定selectedindex是由用户还是代码更改的

run*_*ier 5 .net c# winforms

我在Windows窗体项目中有一个组合框,其中一个事件附加到selectedindex已更改事件.当从代码和用户输入更改selectedindex时,将触发事件.如何检测selectedindex是否因用户输入而发生变化?

stu*_*rtd 10

您可以使用SelectionChangeCommitted事件吗?

仅当用户更改组合框选择时才会引发SelectionChangeCommitted

编辑:SelectionChangeCommitted事件有一个重大失败:如果您使用F4下拉列表然后鼠标悬停在您的选择上并使用Tab键转到下一个控件,它不会触发.

Connect上有一个[关闭并删除]的bug ,它建议使用该DropDownClosed事件来捕获这个cormer案例.


jtd*_*ubs 5

在UI更改传播到模型之前,我已经陷入困境,然后模型更改传播回UI并创建无限循环.你在处理类似的事情吗?

如果是这样,一种方法是仅在模型不同时才从模型更新UI.那是:

if (comboBox.SelectedItem != newValue)
    comboBox.SelectedItem = newValue;
Run Code Online (Sandbox Code Playgroud)

如果这不能得到你想要的,另一种选择是临时删除事件处理程序:

comboBox.SelectedIndexChanged -= this.comboBox_SelectedIndexChanged;
comboBox.SelectedIndex = newIndex;
comboBox.SelectedIndexChanged += this.comboBox_SelectedIndexChanged;
Run Code Online (Sandbox Code Playgroud)

或者,指示处理程序忽略此事件:

ignoreComboBoxEvents = true;
comboBox.SelectedIndex = newIndex;
ignoreComboBoxEvents = false;
...
public void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    if (ignoreComboBoxEvents)
        return;
    ...
}
Run Code Online (Sandbox Code Playgroud)