Goal: issue an event when items in a combobox drop down list is selected.
Problem: Using "SelectionChanged", however, if the user choose the same item as the item is currently being selected then the selection is not changed and therefore this event will not be triggered.
Question: What other event handler(or other ways) I may use to issue an event regardless of the selected item is changed or not as long as the mouse clicked on that item and that item is being selected.
(Clarification: Problem is how to trigger "something" when the same item is being selected again. No duplicates in the drop down list. Scenario: first time select item 1,close drop down. And then again, open drop down box and select item 1 when some function are triggered.)
Solution: for now there seems to be no straight-forward solution to do this. But according to each individual project, there can be ways to work around it. (Please update if there are indeed good ways to do this). Thanks.
You can use "ComboBoxItem. PreviewMouseDown" event.
The ComboBox class searches for the specified object by using the IndexOf method.
Combo boxes also generate item events, which are fired when any of the items' selection state changes. Only one item at a time can be selected in a combo box, so when the user makes a new selection the previously selected item becomes unselected.
Using an enum to fill a combo box allows for easy use of the SelectedItem method to programmatically select items in the combobox as well as loading and reading from the combobox.
I had the same question and I finally found the answer:
You need to handle BOTH the SelectionChanged event and the DropDownClosed like this:
In XAML:
<ComboBox Name="cmbSelect" SelectionChanged="ComboBox_SelectionChanged" DropDownClosed="ComboBox_DropDownClosed"> <ComboBoxItem>1</ComboBoxItem> <ComboBoxItem>2</ComboBoxItem> <ComboBoxItem>3</ComboBoxItem> </ComboBox>
In C#:
private bool handle = true; private void ComboBox_DropDownClosed(object sender, EventArgs e) { if(handle)Handle(); handle = true; } private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { ComboBox cmb = sender as ComboBox; handle = !cmb.IsDropDownOpen; Handle(); } private void Handle() { switch (cmbSelect.SelectedItem.ToString().Split(new string[] { ": " }, StringSplitOptions.None).Last()) { case "1": //Handle for the first combobox break; case "2": //Handle for the second combobox break; case "3": //Handle for the third combobox break; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With