I want to execute a command in my viewmodel when the user presses enter in a TextBox. The command works when bound to a button.
<Button Content="Add" Command="{Binding Path=AddCommand}" />
But I can't bring it to work from the TextBox. I tried an Inputbinding, but it didn't work.
<TextBox.InputBindings>
<KeyBinding Command="{Binding Path=AddCommand}" Key="Enter"/>
</TextBox.InputBindings>
I also tried to set the working button as default, but it doesn't get executed when enter is pressed.
Thanks for your help.
I know I am late to the party, but I got this to work for me. Try using
Key="Return"
instead ofKey="Enter"
Here is the full example
Make sure to use
UpdateSourceTrigger=PropertyChanged
in your binding, otherwise the property will not be updated until focus is lost, and pressing enter will not lose focus...Hope this was helpful!
You have probably not made the command a property, but a field. It only works to bind to properties. Change your AddCommand to a property and it will work. (Your XAML works fine for me with a property instead of a field for the command -> no need for any code behind!)
Here's an attached dependency property I created for this. It has the advantage of ensuring that your text binding is updated back to the ViewModel before the command fires (useful for silverlight which doesn't support the property changed update source trigger).
You use it like this:
You need to define Gesture instead of Key property of the KeyBinding:
In addition to Mark Heath's answer, I took the class one step further by implementing Command Parameter attached property in this way;
Usage: