views:

37

answers:

2

Hi.
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.

+2  A: 

Here is one approach, if you're willing to use a little codebehind:

In the XAML, bind to the command and subscribe to the KeyDown event.

  <TextBox app:Window1.TextBoxPressEnterCommand="{Binding AddCommand}" 
      KeyDown="TextBox_KeyDown" />

In the codebehind, handle the KeyDown event by checking for Enter, and executing the command bound to the TextBox. With the attached dependency property, you can bind different textboxes to different ICommand objects.

public partial class Window1 : Window
{
    public Window1() { InitializeComponent(); }

      // event handler for KeyDown event
    private void TextBox_KeyDown(object sender, KeyEventArgs e)
    {
            // if user didn't press Enter, do nothing
        if (!e.Key.Equals(Key.Enter)) return;

            // execute the command, if it exists
            var cmd = GetTextBoxPressEnterCommand((TextBox) sender);
            if(cmd != null) cmd.Execute(null);
    }

      // declare an attached dependency property
    public static ICommand GetTextBoxPressEnterCommand(TextBox obj)
    {
        return (ICommand)obj.GetValue(TextBoxPressEnterCommandProperty);
    }
    public static void SetTextBoxPressEnterCommand(TextBox obj, ICommand value)
    {
        obj.SetValue(TextBoxPressEnterCommandProperty, value);
    }
    public static readonly DependencyProperty TextBoxPressEnterCommandProperty =
        DependencyProperty.RegisterAttached("TextBoxPressEnterCommand", typeof(ICommand), typeof(Window1));

}
Jay