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.
CodePudding user response:
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 onm ouseDown(object sender, MouseButtonEventArgs e)
{
Keyboard.Focus(sender as Image);
}
CodePudding user response:
Is it necessary for you to use canvas as panel control? You can use for example grid instead. As I know there are some troubles with processing keyboard input in canvas child elements. Also there are problems with canvas remeasuring on changing child elements size. Or you can apply solution from zaphod-ii answer (https://stackoverflow.com/a/72558206/12566464)