Command for WPF TextBox that fires up when we hit Enter Key

Aryan SuryaWansi picture Aryan SuryaWansi · Jul 30, 2011 · Viewed 74.6k times · Source

It is very easy to bind Buttons in WPF apps to Commands in a VIEWMODEL class. I'd like to achieve a similar binding for a TextBox.

I have a TextBox and I need to bind it to a Command that fires up when I hit Enter while the TextBox is focused. Currently, I'm using the following handler for the KeyUp event, but it looks ugly... and I can't put it in my VIEWMODEL class.

private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Key == System.Windows.Input.Key.Enter)
    {
        // your event handler here
        e.Handled = true;
        MessageBox.Show("Enter Key is pressed!");
    }
}

Is there a better way to do this?

Answer

sarh picture sarh · May 5, 2012

I've faced with the same problem and found solution here, here is the code sample:

<TextBox>
  <TextBox.InputBindings>
    <KeyBinding Command="{Binding Path=CmdSomething}" Key="Enter" />
  </TextBox.InputBindings>
</TextBox>