Search code examples
c#wpfeventstextboxcommand

How can I make a textbox listening to a Keypress-Event and an InputBinding together


I created a login-site in my program in WPF where you enter your credentials and then press Enter or the button below. The button has a command (for View Model Binding) and a Click-Event (I got an AutoResetEvent in Code Behind that shakes the Textbox if the login wasn't successful within a second).

Now I tried the same with the Textbox: Command and Event. So this is my Textbox at the moment:

<TextBox Margin="0,0,0,10" Text="{Binding Username}" KeyDown="MainWindow_KeyDown">
                <TextBox.InputBindings>
                    <KeyBinding
                            Key="Enter"
                            Command="{Binding KeyPressCommand}" />
                </TextBox.InputBindings>
            </TextBox>

And this is my button:

<Button Command="{Binding ConnectCommand}" Content="Connect" Background="#E9712F" Margin="0,10,0,0" FontFamily="Arial" FontWeight="Bold" Foreground="White" Cursor="Hand" Click="Button_Click"/>

The button works, it triggers the event and sends the command. But the Textbox completely ignores the Event and just sends the Command to the View Model.

Is there a way to trigger both, event and command?


Solution

  • Instead of KeyDown event Use PreviewKeyDown

    UPDATED

    The KeyDown event is not raised for navigational keys that would normally be handled by WPF, but the PreviewKeyDown event also support those keys.

    Maybe helpful: What are WPF Preview Events?