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?
You can use the IsDefault property of the button:
<Button Command="SearchCommand" IsDefault="{Binding ElementName=SearchTextBox,
Path=IsKeyboardFocused}">
Search!
</Button>
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>
The Prism Reference Implementation contains an implementation of exactly what you are after.
The basics steps are:
This enables you to use the behavior like so:
<TextBox prefix:EnterKey.Command="{Binding Path=SearchCommand}" />
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