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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 10:07:43

问题


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?


回答1:


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?



来源:https://stackoverflow.com/questions/57352813/how-can-i-make-a-textbox-listening-to-a-keypress-event-and-an-inputbinding-toget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!