Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF autocompletebox and the enter key

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?

like image 913
A.R. Avatar asked Feb 14 '11 20:02

A.R.


2 Answers

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)
{

}
like image 149
Jay Avatar answered Sep 22 '22 08:09

Jay


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)
    {
        //...
    }
}
like image 41
Evans Avatar answered Sep 20 '22 08:09

Evans