[英]How To Control Keyboard Focus Inside a UserControl
I have a simple UserControl
Which contains some TextBlock
s. 我有一个简单的UserControl
其中包含一些TextBlock
。 Also I have some of my UserControl
s in a StackPanel
, Normally when I press arrow keys keyboard focus moves between UserControl
s and that's the behavior I DON"T WANT. 另外,我在StackPanel
还有一些UserControl
,通常当我按箭头键时,键盘焦点会在UserControl
之间移动,这就是我不希望的行为。
I want to handle arrow keys press inside the UserControl
and stop keyboard navigation normal behavior, Just like a TextBox
. 我想处理UserControl
内的箭头键按下并停止键盘导航的正常行为,就像TextBox
。 How Can I Do That? 我怎样才能做到这一点?
<StackPanel >
<dtp:DatePicker VerticalAlignment="Top"/> <!-- When I press down arrow key on this element, keyboard navigation moves to next element-->
<dtp:DatePicker VerticalAlignment="Top" DisplayType="DateOnly"/>
<dtp:DatePicker VerticalAlignment="Top" DisplayType="TimeOnly"/>
<dtp:DatePicker VerticalAlignment="Top" HasSeconds="False"/>
<dtp:DatePicker VerticalAlignment="Top" DisplayType="DateOnly" HasSeconds="False"/>
<dtp:DatePicker VerticalAlignment="Top" DisplayType="TimeOnly" HasSeconds="False"/>
</StackPanel>
Normally, with controls just inside a StackPanel, simple controls don't lost focus when pressing an arrow key. 通常,对于仅位于StackPanel内部的控件,简单的控件在按箭头键时不会失去焦点。 You can try it with just this little test. 您可以通过这个小测试来尝试一下。
<StackPanel>
<DatePicker/>
<DatePicker/>
<DatePicker/>
</StackPanel>
Maybe your problem is outside the dtp:DatePicker
controls. 也许您的问题不在dtp:DatePicker
控件之外。 Maybe you are putting the StackPanel
in an ItemTemplate
? 也许您正在将StackPanel
放在ItemTemplate
?
Anyway, you can try to neutralize the arrow keys with the PreviewKeyUp
event like this : 无论如何,您可以尝试使用PreviewKeyUp
事件中和箭头键,如下所示:
<dtp:DatePicker PreviewKeyUp="OnPreviewKeyUp"/>
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Up || e.Key == Key.Down)
e.Handled = true;
}
Or you can try to put a navigation constraint with Navigation mode : 或者,您可以尝试在导航模式下放置导航约束:
<dtp:DatePicker KeyboardNavigation.DirectionalNavigation="None"
KeyboardNavigation.TabNavigation="None"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.