如何使文本框同时监听Keypress-Event和InputBinding [英] How can I make a textbox listening to a Keypress-Event and an InputBinding together
问题描述
我在WPF中的程序中创建了一个登录站点,您在其中输入凭据,然后按Enter或下面的按钮。该按钮具有一个命令(用于View模型绑定)和一个Click-Event(在代码隐藏中提供了一个AutoResetEvent,如果在一秒钟内登录失败,该动摇文本框)。
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>
这是我的按钮:
<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?
推荐答案
代替 KeyDown
事件使用 PreviewKeyDown
更新
KeyDown $通常不会由WPF处理的导航键不会引发c $ c>事件,但是
PreviewKeyDown
事件也支持这些键。
The KeyDown
event is not raised for navigational keys that would normally be handled by WPF, but the PreviewKeyDown
event also support those keys.
可能有帮助:什么是WPF预览事件?
这篇关于如何使文本框同时监听Keypress-Event和InputBinding的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!