2011-02-14 22 views
6

Estoy intentando que WPF AutoCompleteBox levante el evento KeyDown al presionar la tecla enter. Estoy usando el gancho KeyDown normal, que funciona para todo menos la tecla Intro parece. ¿Alguien sabe como puedo arreglar esto?WPF autocompletebox y la tecla enter

+0

¿Qué desea que haga al presionar la tecla Entrar? – Jay

+0

?? ¡Quiero que vea el evento! –

+0

¿Has probado PreviewKeyDown? – Ragepotato

Respuesta

10

Puede heredar el AutoCompleteBox, agregando un evento para Ingrese.

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); 
    } 
} 

En su clase consumidora, puede suscribirse:

public void Subscribe() 
{ 
    autoCompleteBox.EnterKeyDown += DoSomethingWhenEnterPressed; 
} 

public void DoSomethingWhenEnterPressed(object sender) 
{ 

} 
+0

Bueno, es un dolor, pero supongo que funciona. Ojalá hubiera una manera más fácil. Gracias sin embargo. –

4

Hay es una manera un poco más fácil (y en mi opinión más MVVM):

// 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); 
     } 

Esto minimiza la código subyacente blasfemo y permite que su evento clave continúe burbujeando hasta algo así como un enlace de entrada:

<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> 
+0

Esta sería una solución encantadora, si solo las asociaciones de teclas para 'Enter' o 'Return' funcionaran de manera confiable. Pero parece que dependiendo de la configuración 'AutoCompleteBox's, estos son ignorados. – stakx

-1

Por otra parte, cuando se utiliza Caliburn Micro, puede simplemente usar:

<Controls:AutoCompleteBox ItemsSource="{Binding Keywords}" 
          ValueMemberPath="Name"     
          Text="{Binding EnteredText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
          IsTextCompletionEnabled="True" 
          cal:Message.Attach="[Event PreviewKeyDown] = [Action AddTagOnEnter($eventArgs)]" /> 

En concreto, tenga en cuenta la última línea para conectar el evento. Para algunas otras opciones de parámetros de método, vea here.

Por último, definir un método público en su modelo de vista:

public void AddTagOnEnter(KeyEventArgs e) 
{ 
    if (e.Key != Key.Enter) return; 
    // Do something useful 
} 
8

respuesta muy tarde, pero enfrentado a este mismo problema que me trajo a esta pregunta y finalmente lo resolvió mediante PreviewKeyDown

<wpftoolkit:AutoCompleteBox Name="AutoCompleteBoxCardName" 
    Populating="LoadAutocomplete" 
    PreviewKeyDown="AutoCompleteBoxName_PreviewKeyDown"/> 

y

private void AutoCompleteBoxName_PreviewKeyDown(object sender, KeyEventArgs e) 
{ 
    if (e.Key == Key.Enter) 
    { 
     //... 
    } 
} 
+0

Buena llamada. Eventualmente resolví mi problema y otros que aparecieron escribiendo mi propio control de cuadro de autocompletar. –

1

(Sé que esta es una respuesta tardía, pero todavía creo que ' s muy útil para las personas que quieren resolver este problema, sin código detrás)

Una buena manera de hacer esto en MVVM

Primero se debe agregar la referencia:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 

y desde el NuGet paquete (MVVMLight):

xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras" 

Que en su Ver:

<wpftoolkit:AutoCompleteBox Name="AutoCompleteBoxName"> 
    <i:Interaction.Triggers> 
        <i:EventTrigger EventName="PreviewKeyDown"> 
         <cmd:EventToCommand Command="{Binding AutoCompleteEnter}" PassEventArgsToCommand="True"/> 
        </i:EventTrigger> 
       </i:Interaction.Triggers> 
</wpftoolkit:AutoCompleteBox> 

y que en su modelo de vista :

public ICommand AutoCompleteEnter { get { return new RelayCommand<System.Windows.Input.KeyEventArgs>(Auto_Complete_Enter); } } 

public void Auto_Complete_Enter(System.Windows.Input.KeyEventArgs e) 
{ 
    //Detect if key is 'Enter/Return' key 
    if ((e.Key == Key.Enter) || (e.Key == Key.Return)) 
    { 
     Console.WriteLine("U have pressed the enter key"); 
    } 
} 

Hope esto todavía le ayudará a algunas personas.

Cuestiones relacionadas