Invoke Command When "ENTER" Key Is Pressed In XAML

Posted by bitxwise on Stack Overflow See other posts from Stack Overflow or by bitxwise
Published on 2011-01-29T00:10:11Z Indexed on 2011/03/11 0:10 UTC
Read the original article Hit count: 193

I want to invoke a command when ENTER is pressed in a TextBox. Consider the following XAML:

<UserControl
     ...
     xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
     ...>    
     ...    
     <TextBox>
          <i:Interaction.Triggers>
               <i:EventTrigger EventName="KeyUp">
                    <i:InvokeCommandAction Command="{Binding MyCommand}"
                                           CommandParameter="{Binding Text}" />
               </i:EventTrigger>
          </i:Interaction.Triggers>
     </TextBox>    
     ...    
</UserControl>

and that MyCommand is as follows:

public ICommand MyCommand {
     get { return new DelegateCommand<string>(MyCommandExecute); }
}

private void MyCommandExecute(string s) { ... }

With the above, my command is invoked for every key press. How can I restrict the command to only invoke when the ENTER key is pressed?

I understand that with Expression Blend I can use Conditions but those seem to be restricted to elements and can't consider event arguments.

I have also come across SLEX which offers its own InvokeCommandAction implementation that is built on top of the Systems.Windows.Interactivity implementation and can do what I need. Another consideration is to write my own trigger, but I'm hoping there's a way to do it without using external toolkits.

© Stack Overflow or respective owner

Related posts about Silverlight

Related posts about xaml