Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Execute a Command Binding in a search field when pressing the enter button

I have a search field in my WPF app with a search button that contains a command binding. This works great, but how can i use the same command binding for the text field when pressing enter on the keyboard? The examples I have seen are all using the Code behind with a KeyDown Event Handler. Is there a smart way to make this work only with xaml and command binding?

like image 889
code-zoop Avatar asked Oct 19 '09 08:10

code-zoop


3 Answers

You can use the IsDefault property of the button:

    <Button Command="SearchCommand" IsDefault="{Binding ElementName=SearchTextBox,
                                               Path=IsKeyboardFocused}">
         Search!
   </Button>
like image 195
Dabblernl Avatar answered Oct 24 '22 16:10

Dabblernl


The accepted answer only works if you already have a button bound to the command.

To avoid this limitation, use TextBox.InputBindings:

<TextBox.InputBindings>
    <KeyBinding Key="Enter" Command="{Binding Path=MyCommand}"></KeyBinding>
</TextBox.InputBindings>
like image 22
Greg Sansom Avatar answered Oct 24 '22 14:10

Greg Sansom


The Prism Reference Implementation contains an implementation of exactly what you are after.

The basics steps are:

  • Create a static class EnterKey
  • Registered attached property "Command" of type ICommand on EnterKey
  • Registered attached property "EnterKeyCommandBehavior" of type EnterKeyCommandBehavior on EnterKey
  • When the value of "Command" changes, attach "EnterKeyCommandBehavior" to the control as a new instance of EnterKeyCommandBehavior, and assign the ICommand to the behavior's Command property.
    • If the behavior is already attached, use the existing instance
  • EnterKeyCommandBehavior accepts a UIElement in the constructor and attaches to the PreviewKeyDown (or KeyDown if you want to stay Silverlight compatible).
  • In the event handler, if the key is Enter, execute the ICommand (if CanExecute is true).

This enables you to use the behavior like so:

<TextBox prefix:EnterKey.Command="{Binding Path=SearchCommand}" />
like image 20
Richard Szalay Avatar answered Oct 24 '22 15:10

Richard Szalay