I am trying to get the WPF AutoCompleteBox to raise the KeyDown event when I press the enter key. I am using the normal KeyDown hook, which works for everything but the enter key it seems. Does anyone know how I can fix this?
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)
{
//...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With