Reputation: 13302
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.
Upvotes: 3
Views: 2569
Reputation: 118
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;
}
}
}
Upvotes: 1
Reputation: 1029
Try this
// prevent selecting an item when a comboboxitem is highlighted
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Enter || e.Key == System.Windows.Input.Key.Return)
{
e.Handled = true;
}
else
{
//if (base.IsDropDownOpen == false)
//{
// base.IsDropDownOpen = true;
//}
}
//base.OnPreviewKeyDown(e);
}
Upvotes: 0