开发者

Windows Forms how to find out if selectedindex was changed by user or by code

I hav开发者_高级运维e a combobox in a Windows Forms project with an event attached to the selectedindex changed event. The event is getting triggered when the selectedindex is changed both from code and from user input. How do you detect if the selectedindex is getting changed due to user input?


Can you use the SelectionChangeCommitted event instead?

SelectionChangeCommitted is raised only when the user changes the combo box selection

EDIT: The SelectionChangeCommitted event has a major failing: if you use F4 to drop down the list then mouse over your selection and use the Tab key to go to the next control, it does not fire.

There's a [closed and deleted] bug on Connect about it, which suggests using the DropDownClosed event as well to catch this edge case.


I've gotten stuck in situations before where a UI change propagates to the Model, then the Model change propagates back to the UI and it creates an endless cycle. Are you dealing with something like that?

If so, one way out is to only update the UI from the model only if they differ. That is:

if (comboBox.SelectedItem != newValue)
    comboBox.SelectedItem = newValue;

If that doesn't get you what you want, another option is to temporarily remove the event handler:

comboBox.SelectedIndexChanged -= this.comboBox_SelectedIndexChanged;
comboBox.SelectedIndex = newIndex;
comboBox.SelectedIndexChanged += this.comboBox_SelectedIndexChanged;

or, instruct the handler to ignore this event:

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


Your event handler is only called after user input, and not after code changing the index. Either handle that case there, or set a boolean flag there saying it was user input so that another part of the code can see that the last index change was due to user input.


You can set a boolean flag whenever the selectedindex is changed by the code, and the handler can abort (resetting the flag) whenever that flag is set.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜