Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ComboBox PreviewKeyDown doesn't fire for Return key

I'm want to conditionally prevent the Enter/Return key from selecting the highlighted item in a ComboBox drop down. So I wired up an event handler to the ComboBox.PreviewKeyDown so that I could set the Handled property, but the event handler is never entered. When I use Snoop to watch the events, the PreviewKeyDown event is fired for other keys but it never fires when I press the return key; not even at the Window level. Why isn't the event firing?

EDIT: The ComboBox needs to be editable (IsEditable=true). Then open the drop down list. Begin typing in an item in your list and it should select it for you. Press the return key.

like image 761
xr280xr Avatar asked Feb 03 '26 06:02

xr280xr


1 Answers

That's because WPF internally handles the event when the drop-down is open and enter key is pressed. That's the default WPF behavior.

To solve, extend the ComboBox and override the OnPreviewKeyDown method.

public class MyComboBox : ComboBox
{
    protected override void OnPreviewKeyDown(KeyEventArgs e)
    {
        bool isDropDownOpen = IsDropDownOpen;

        base.OnPreviewKeyDown(e);

        if (isDropDownOpen)
        {
            e.Handled = false;
        }
    }
}
like image 139
CaesarMyMate Avatar answered Feb 05 '26 01:02

CaesarMyMate