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