Voici une approche, si vous êtes prêt à utiliser un peu de code derrière :
Dans le XAML, liez la commande et souscrivez à l'événement KeyDown.
<TextBox app:Window1.TextBoxPressEnterCommand="{Binding AddCommand}"
KeyDown="TextBox_KeyDown" />
Dans le codebehind, traitez l'événement KeyDown en vérifiant la présence d'Enter et en exécutant la commande liée à la TextBox. Grâce à la propriété de dépendance jointe, vous pouvez lier différentes textboxes à différentes commandes ICommand
objets.
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));
}