问题
I have several comboboxes in a UI each with a long list of similar entries (numbers). When the user selects an item from one of the comboboxes, I know the user will choose an entry with a similar value (but likely not the same) from the other comboboxes. Thus, after the user has selected a value, to help avoid forcing the user to do a lot of scrolling, I would like to "pre-scroll" the next combobox dropdown to the vicinity of the last selected value (when this dropdown does not already have a selection).
I have accomplished this thus far by using
combobox.SelectedItem = myLastSelectedItem;
inside a combobox.DropDown event handler.
Then, when the dropdown closes, I need to be able to detect if the user clicked on an item from the dropdown or not. If the user did not click on an item, then I must reset the selected value to what it was before (nothing). The user could have clicked on myLastSelectedItem or a different item (thus, I can't just compare the current selected item to myLastSelectedItem, as they may be the same even if the user did click). SelectedValueChange, SelectedIndexChange, TextChanged all get fired after the DropDownClosed event, thus I cannot use them. The MouseClick event does not get fired at all.
Thus, how do I detect that the user clicked on an item in a combobox dropdown (as opposed to the dropdown closing because the user clicked outside of it, or pressed escape)?
回答1:
I tried my best to see if I could make this work, but I'll be damned if I wasn't pulling my hair out after 30 minutes of it. If you were open to a little bit of change, you could try using the ListBox control. It has a "TopIndex" property that scrolls to the index you want but never actually makes a selection. See below code:
private void listBox_SelectedIndexChanged(object sender, EventArgs e) {
ListBox lbx = sender as ListBox;
if (lbx != null) {
switch (lbx.Name) {
case "listBox1":
listBox2.TopIndex = lbx.SelectedIndex;
listBox2.SelectedIndex = -1;
listBox3.TopIndex = 0;
listBox4.TopIndex = 0;
break;
case "listBox2":
listBox3.TopIndex = lbx.SelectedIndex;
listBox3.SelectedIndex = -1;
listBox4.TopIndex = 0;
break;
case "listBox3":
listBox4.TopIndex = lbx.SelectedIndex;
listBox4.SelectedIndex = -1;
break;
}
}
}
with 4 different ListBox controls all using that on their SelectedIndexChanged event. Let me know if that works or not. If not I can go back to the ComboBoxes.
来源:https://stackoverflow.com/questions/12640438/detecting-user-selection-in-combobox-dropdownclosed-in-winforms