WPF autocompletebox and the enter key
You could inherit the AutoCompleteBox
, adding an event for Enter.
public class MyAutoCompleteBox : AutoCompleteBox
{
public override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if(e.Key == Key.Enter) RaiseEnterKeyDownEvent();
}
public event Action<object> EnterKeyDown;
private void RaiseEnterKeyDownEvent()
{
var handler = EnterKeyDown;
if(handler != null) handler(this);
}
}
In your consuming class, you can subscribe:
public void Subscribe()
{
autoCompleteBox.EnterKeyDown += DoSomethingWhenEnterPressed;
}
public void DoSomethingWhenEnterPressed(object sender)
{
}
Very late answer, but I faced this same problem that brought me to this question and finally solved it using PreviewKeyDown
<wpftoolkit:AutoCompleteBox Name="AutoCompleteBoxCardName"
Populating="LoadAutocomplete"
PreviewKeyDown="AutoCompleteBoxName_PreviewKeyDown"/>
and
private void AutoCompleteBoxName_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
//...
}
}
There is a slightly easier (and in my opinion more MVVM) way:
// This still goes in your code behind (yuck!)
protected override void OnKeyDown(KeyEventArgs e)
{
if (!IsDropDownOpen && SelectedItem != null && (e.Key == Key.Enter || e.Key == Key.Return))
{
// Drop down is closed so the item in the textbox should be submitted with a press of the Enter key
base.OnKeyDown(e); // This has to happen before we mark Handled = false
e.Handled = false; // Set Handled = false so the event bubbles up to your inputbindings
return;
}
// Drop down is open so user must be selecting an AutoComplete list item
base.OnKeyDown(e);
}
This minimizes the blasphemous code-behind and allows your key event to continue to bubble up to something like an input binding:
<UserControl.InputBindings>
<KeyBinding Key="Tab" Command="{Binding NextCommand}"/>
<KeyBinding Key="Tab" Modifiers="Shift" Command="{Binding LastCommand}"/>
<KeyBinding Key="Escape" Command="{Binding ClearCommand}"/>
<KeyBinding Key="Enter" Command="{Binding EnterCommand}"/>
</UserControl.InputBindings>