Search code examples
c#wpf

WPF Keydown event on user Control not working


Keydown, Perview Keydown, Keyup Perview Keyup none of these seem to work at all. I cant even tap over to my Image.

here is my code:

<Viewbox Width="auto" Height="auto" >
    <Border ClipToBounds="True">
        <Canvas Height="50" Width="50" x:Name="comicbookBorder"
            MouseWheel="comicbookSource_OnMouseWheel"
            MouseMove="comicbookSource_OnMouseMove"
            MouseDown="CanvasGridScreen_MouseDown"
            Mouse.MouseUp="CanvasGridScreen_MouseUp"
            MouseLeftButtonUp="comicbookSource_OnMouseLeftButtonUp">
             
            <Image x:Name="comicbookSource"
                PreviewKeyUp="comicbookBorder_KeyDown"
                Width="{Binding Path=ActualWidth, ElementName=comicbookBorder}"
                Height="{Binding Path=ActualHeight, ElementName=comicbookBorder}"
                Stretch="Uniform" Loaded="comicbookSource_Loaded"/>
        </Canvas>
    </Border>
</Viewbox>

All of the other events work, but nothing of the Key down/ up will work. If I add a textbox then that works, but I am trying to display an image, I do not want a random textbox in the middle of my image that you have to click on.


Solution

  • Check the article about keyboard focus, it sheds some light on the essence of the problem. In brief, Image is has its Focusable property set to false by default. To allow the element to take keyboard focus by any means, it should be set to true. Then you should manage the focus state of the image by using the Keyboard.Focus method. This should be working fine for passing the focus on mouse click:

    <Image Focusable="True" PreviewKeyDown="OnKeyDown" MouseDown="OnMouseDown"... />
    

    and then in code-behind:

    private void OnMouseDown(object sender, MouseButtonEventArgs e)
    {
       Keyboard.Focus(sender as Image);
    }