WPF FocusNavigationDirection, MoveFocus and Arrow keys(WPF FocusNavigationDirection、MoveFocus 和箭头键)
问题描述
我有一个简单的应用程序(一个带有 6 个按钮的网格 - 2 行 3 个 - 用于测试)并且正在按如下方式处理左右箭头键
I have a simple application (a grid with 6 buttons - 2 rows of 3 - on it for testing) and am handling left and right arrow keys as follows
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
FocusNavigationDirection focusDirection = new System.Windows.Input.FocusNavigationDirection();
switch (e.Key)
{
case Key.Left:
focusDirection = System.Windows.Input.FocusNavigationDirection.Left;
break;
case Key.Right:
focusDirection = System.Windows.Input.FocusNavigationDirection.Right;
break;
default:
break;
}
TraversalRequest request = new TraversalRequest(focusDirection);
// Gets the element with keyboard focus.
UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;
// Change keyboard focus.
if (elementWithFocus != null)
{
elementWithFocus.MoveFocus(request);
}
}
不幸的是,这并不像我预期的那样,因为焦点似乎总是朝着与 FocusNavigationDirection 指定的方向相反的方向移动.
Unfortunately, this doesn't behave as I expect as the focus always seems to move in the opposite direction to that specified by the FocusNavigationDirection.
对为什么会这样有什么想法吗?MSDN Documentation 有点含糊左侧"是如何定义的.
Any thoughts on why this would be? The MSDN Documentation is a bit vague on how "to the left of" is defined.
如果需要,我还将每个按钮的制表位定义为 1 到 6.
In case it is needed, I have also defined the tab stops of each of the buttons as 1 through 6.
推荐答案
为什么要获取 elementWithFocus 而可以使用this"(window own scope)?
Why do you need to get the elementWithFocus while you can use "this" (window own scope)?
我稍微修改了你的代码,它对我有用:
I modified your code a bit and it worked for me:
private void Window_OnPreviewKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Left:
this.MoveFocus(FocusNavigationDirection.Previous);
break;
case Key.Right:
this.MoveFocus(FocusNavigationDirection.Next);
break;
default:
break;
}
}
private void MoveFocus(FocusNavigationDirection direction)
{
var request = new TraversalRequest(direction);
this.MoveFocus(request);
}
这篇关于WPF FocusNavigationDirection、MoveFocus 和箭头键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:WPF FocusNavigationDirection、MoveFocus 和箭头键


基础教程推荐
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何激活MC67中的红灯 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01