KeyDown事件不会从UWP中的选定网格触发 [英] KeyDown event doesn't trigger from selected grid in UWP
问题描述
我正在使用自定义控件(如日历),在该控件中有一个面板作为月视图,其中网格单元格排列为日期单元格.网格具有一个内容呈现器,其中TextBlock作为内容模板.一切正常. Pointerpressed,pointerReleased和OnTapped重写方法在Grid上正常工作,但是OnKeyDown重写方法或KeyDown事件不会从中触发.我也尝试过使用PreviewKeyDown.请帮助我解决这个问题.
I'm working on custom control like calendar, where I have a panel as month view in which Grid cells are arranged as Date cells. The grid has a content presenter with TextBlock as a content template. Everything working fine. Pointerpressed, pointerReleased and OnTapped override methods are working fine for Grid but OnKeyDown override method or KeyDown event doesn't trigger from it. I also tried with PreviewKeyDown. Please help me to overcome this issue.
推荐答案
按键事件仅从以键盘为中心的控件中触发.网格不是控件,而网格是面板.在UWP中,只有控件可以设置焦点.
The key down event only trigger from keyboard focused control. And the Grid is not a control and the Grid is Panel. In UWP, only the control can set focus.
您可以编写一个空控件并将其添加到Grid中以设置控件焦点.
You can write a empty control and add it to Grid to set the control focus.
class Foo : Control
{
protected override void OnKeyDown(KeyRoutedEventArgs e)
{
Debug.WriteLine("Foo key down");
}
}
<Grid x:Name="Grid2" Margin="10,10,10,10" Width="100" Background="#565656" HorizontalAlignment="Right"
KeyDown="Grid2_OnKeyDown">
<local:Foo x:Name="Foo"></local:Foo>
</Grid>
当Grid2键按下时,您可以编写任何代码来帮助调试.
You can write any code to help debug when the Grid2 key down.
private void Grid2_OnKeyDown(object sender, KeyRoutedEventArgs e)
{
Debug.WriteLine("Grid2 key down");
}
然后您可以在单击Grid2时设置Foo属性焦点.
And then you can set the Foo property focus when the Grid2 clicked.
private async void Grid2_OnPointerReleased(object sender, PointerRoutedEventArgs e)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Foo.Focus(FocusState.Keyboard); });
}
尝试运行代码,当您单击Grid2并按键时,您会看到输出窗口显示该消息.
Try to run the code and you can see the output windows show the message when you click the Grid2 and press key.
但是为什么我要在调度程序中编写代码,因为我应该使Foo控件获得焦点.而且,如果我不使用调度程序,则指针焦点将位于Grid中,而不是任何UIElement焦点键盘中.
But why I write the code in dispatcher, because I should make the Foo control get focus. And if I do not use dispatcher and the pointer focus will in Grid and not any UIElement focus keyboard.
这篇关于KeyDown事件不会从UWP中的选定网格触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!