为什么 KeyDown 对我的控件不起作用,而是对整个窗体起作用?

Why KeyDown is not working on my control, but on the whole form?

我正在使用此例程来检查我的 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 上设置 时,它 命中 s:

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

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

Only the focused element receives keyboard input.

另外值得注意的是:

When deriving from UIElement directly (as opposed to from Control), consider whether you wish your element to be focusable, because by default the element will not be focusable. If you wish your element to be focusable, override the metadata for this property within your type's static constructor as follows:

Image class documentation可以看出它是从UIElement派生的,而不是Control,所以默认情况下它不能接收焦点。

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