3
votes

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?

1
Seems I was off with the Enter. Sorry for thatNoctis

1 Answers

2
votes

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;
    }
}