【问题标题】:Why KeyDown is not working on my control, but on the whole form?为什么 KeyDown 不在我的控件上工作,而是在整个表单上工作?
【发布时间】:2016-11-23 21:34:12
【问题描述】:

我正在使用这个例程来检查我的图像控件上是否按下了我的LeftCtrl 键:

private void mainImage_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.LeftCtrl)
    {
        LeftCtrlButtonIsPressed = true;
    }
}

private void mainImage_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Key == Key.LeftCtrl)
    {
        LeftCtrlButtonIsPressed = false;
    }
}

当我将事件设置在图像或图像周围的边框上时,它不会命中

<Border x:Name="mainImageBackBorder" .... KeyDown="mainImage_KeyDown" KeyUp="mainImage_KeyUp"> <! -- Does not Hit -->
    <Image x:Name="mainImage" ... KeyDown="mainImage_KeyDown" KeyUp="mainImage_KeyUp"> <! -- Does not Hit -->
        <Image.RenderTransform>
            <! -- ... -->
        </Image.RenderTransform>
    </Image>
</Border>

但是,当我将它设置在我的窗口上时,它命中

<Window x:Class="ProjectName.MainWindow"
        ..
        DataContext="{StaticResource mainViewModel }"
        Title="MainWindow" Height="600" Width="800" KeyDown="mainImage_KeyDown" KeyUp="mainImage_KeyUp"> <!-- It Hits -->

【问题讨论】:

    标签: c# wpf xaml keyboard keydown


    【解决方案1】:

    您的图像控件将不会接收 KeyDown 事件,因为 Focusable 属性默认设置为 false。从 Focusable 文档的第一行开始:

    只有焦点元素接收键盘输入。

    另外值得注意的是:

    当直接从 UIElement 派生(而不是从 Control)派生时, 考虑你是否希望你的元素是可聚焦的,因为通过 默认元素将不可聚焦。如果你希望你的元素 是可聚焦的,覆盖你的这个属性的元数据 type的静态构造函数如下:

    Image class documentation 可以看出,它源自 UIElement,而不是 Control,因此默认情况下它无法接收焦点。

    如果您使 Image 可聚焦,这应该可以正常工作,但请记住明显的副作用 - 您的用户当前的焦点可能会丢失在没有视觉指示已被选中的 Image 控件上。

    【讨论】:

    • 我明白了。感谢您的帮助:) 我会在未来意识到这一点
    猜你喜欢
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 2023-02-22
    相关资源
    最近更新 更多