What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)
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.
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;
}
}
For me ComboBox.DropDownClosed
Event did it.
private void cbValueType_DropDownClosed(object sender, EventArgs e)
{
if (cbValueType.SelectedIndex == someIntValue) //sel ind already updated
{
// change sel Index of other Combo for example
cbDataType.SelectedIndex = someotherIntValue;
}
}
You can use "ComboBoxItem.PreviewMouseDown" event. So each time when mouse is down on some item this event will be fired.
To add this event in XAML use "ComboBox.ItemContainerStyle" like in next example:
<ComboBox x:Name="MyBox"
ItemsSource="{Binding MyList}"
SelectedValue="{Binding MyItem, Mode=OneWayToSource}" >
<ComboBox.ItemContainerStyle>
<Style>
<EventSetter Event="ComboBoxItem.PreviewMouseDown"
Handler="cmbItem_PreviewMouseDown"/>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
and handle it as usual
void cmbItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
//...do your item selection code here...
}
Thanks to MSDN