'Event when combobox is selected
My question is how to do an action when an ComboBoxItem is Selected in a ComboBox in C# (WPF) ?
In this post they handle the DropDownClosed event but they don't handled the keyboard Selection.
So I explain my case:
The events "Selected" for the ComboBoxItems or "SelectionChanged" for the ComboBox do the action only when the user select an different ComboBoxItem, but I would like that the action be execute even if the ComboBoxItem that the user select is the same that the ComboBoxItem already selected.
I try with "PreviewMouseLeftButtonDown", but if the user select with keyboard or just keep the mouse press and then select, it doesn't work.
In my situation, I have to open a window when I select an Item:
private void cmiCCSelect_Selected(object sender, RoutedEventArgs e)
{
cCEntityWindow.ShowDialog();
}
But if the user close this window and re-select the same Item, it doesn't work. I have to select an other and after re-select the same for the Event "Selected" can be execute.
Can anybody help me?
Solution 1:[1]
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;
}
}
Solution 2:[2]
The trick is to clear the selection after the choosing. This will allow to select the same item multiple times:
private int m_SuspendSelectionChanged;
private void cboPlaceholders_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (m_SuspendSelectionChanged > 0) return;
string placeholder = (string)cboPlaceholders.SelectedItem;
txtFormat.InsertStringAtCursorPosition("{" + placeholder + "}");
// Allow selecting the same item a second time
m_SuspendSelectionChanged++;
cboPlaceholders.SelectedIndex = -1;
m_SuspendSelectionChanged--;
e.Handled = true;
}
The suspend must prevent that the event is processed a second time.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | deltonio2 |
Solution 2 | AndresRohrAtlasInformatik |