Keydown 事件触发两次 [英] Keydown Event fires twice

查看:142
本文介绍了Keydown 事件触发两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Windows 商店应用程序上,我有这个简单的 TextBox

On a Windows store App, I have this simple TextBox

<TextBox Name="TextBoxUser" HorizontalAlignment="Right" Width="147" Margin="20,0,0,0" KeyDown="TextBox_KeyDown" /

有一个与之关联的 KeyDown 事件.

That has a KeyDown Event associated with it.

        private async void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        if (e.Key == Windows.System.VirtualKey.Enter)
        {
           Debug.WriteLine("LA");
        }
    }

这个函数的输出是:


洛杉矶
洛杉矶


LA
LA

虽然我只按了一次 Enter,但它打印了 2 次.有什么原因还是我做错了什么?

although I press Enter only once, it prints 2 times. Any reason for that or am I doing something wrong?

推荐答案

这应该只触发一次事件,所以如果它触发两次,我会检查一些事情.

This should only fire the event once, so if it is firing twice I would check a couple of things.

检查您没有在父控件上处理按键按下事件.这可以是面板或包含窗口.事件将通过可视化树向下冒泡.例如,文本框上的按键也将是包含文本框的窗口上的按键.

Check that you aren't handling the key down event on a parent control. This could be a panel or the containing window. Events will bubble down through the visual tree. For example a key down on a textbox will also be a keydown on the window containing the textbox.

要阻止这种情况发生,您可以将事件标记为已处理,如下所示;

To stop this happening you can mark the event as handled as below;

e.Handled = true;

要检查的另一件事是您没有订阅该活动两次.XAML 将执行相同的操作;

The other thing to check is that you aren't subscribing to the event twice. The XAML will do the same as;

TextBoxUser.KeyDown += TextBox_KeyDown

TextBoxUser.KeyDown += TextBox_KeyDown

因此请检查您的代码中是否没有此内容.

so check that you don't have this in your code behind.

您可以检查 sender 和 e.OriginalSource 属性以查看事件是从哪里触发的.

You can check the sender and e.OriginalSource property to see where the event is being fired from.

这篇关于Keydown 事件触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆