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

C#.NetWpfIcommand

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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>

Solution 2 - C#

Aryan, not every WPF object supports commanding. So if you wan't to do that you'll need either to call your view model from your code behind (a little coupled) or use some MVVM Messaging implementation to decouple that. See MVVM Light Messaging toolkit for an example. Or simple use triggers like this:

<TextBox>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="KeyUp">
            <i:InvokeDataCommand Command="{Binding MyCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</TextBox>

Solution 3 - C#

I like Sarh's answer, but it wouldn't work in my program, unless I changed Enter to Return:

<TextBox>
    <TextBox.InputBindings>
        <KeyBinding Key="Return" Command="{}" />
   </TextBox.InputBindings>
</TextBox>

Solution 4 - C#

<TextBox Text="{Binding FieldThatIAmBindingToo, UpdateSourceTrigger=PropertyChanged}">
    <TextBox.InputBindings>
        <KeyBinding Command="{Binding AddCommand}" Key="Return" />
    </TextBox.InputBindings>
</TextBox>

I took answer from here

Solution 5 - C#

You can set true to AcceptReturn property.

 <TextBox AcceptsReturn="True" />

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAryan SuryaWansiView Question on Stackoverflow
Solution 1 - C#sarhView Answer on Stackoverflow
Solution 2 - C#Erre EfeView Answer on Stackoverflow
Solution 3 - C#Nightmare GamesView Answer on Stackoverflow
Solution 4 - C#Владимир СонныйView Answer on Stackoverflow
Solution 5 - C#KanimozhiView Answer on Stackoverflow