仅当控件通过键盘接收焦点时才绘制焦点矩形

发布于 2024-10-25 03:25:33 字数 1021 浏览 2 评论 0原文

我想设置 TabItem 的“焦点矩形”的样式。我了解到我可以使用 FocusVisualStyle 来做到这一点。问题是 FocusVisualStyle 为绘制在控件顶部的装饰器。我使用复杂的半透明控件和阴影效果,并且需要在属于 TabItem.Template 的某些元素下显示矩形。

我在 MSDN 上发现可以使用 IsKeyboardFocused 结合触发器来实现我所需要的。然而,进一步研究表明这是不正确的,因为:

键盘焦点是指当前正在接收键盘输入的元素。这并不意味着焦点是通过键盘导航设置的。

可能的解决方法之一可能是:

您可以监听key_down事件来检查导航键是否被按下。 WPF 控件在内部执行此操作以显示 FocusVisualStyle。

还有其他更简单的方法来实现我想要做的事情吗?我并不真正喜欢创建隐藏代码、监听事件以及处理所有这些不同的导航键和快捷键。

I want to style a TabItem's "focus rectangle". I've learned I can do this using FocusVisualStyle. The problem is that FocusVisualStyle creates a sepearate visual tree for an adorner that is drawn on top of the control. I use complex semi-transparent controls and drop-shadow effects, and I need to show the rectangle under certain elements that are part of the TabItem.Template.

I've found on MSDN that I can use IsKeyboardFocused combined with trigger to achieve what I need. However further research have shown this is not correct, because:

Keyboard focus refer to the element that is currently receiveing keyboard input. It doesn't mean the focus is set via a keyboard navigation.

One of the possible workaround might be:

You can listen to key_down events to check whether an navigation key is pressed. WPF controls do this internally to display the FocusVisualStyle.

Is there any other, easier way to achieve what I'm trying to do? I'm not really into creating code behind, listening for events and handling all of these many different navigation keys and shortcuts.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

山人契 2024-11-01 03:25:33

默认情况下,FrameworkElement 检查 OnGotKeyboardFocus。如果最后一个输入设备是键盘,则它显示 FocusVisualStyle。

您可以通过为 GotKeyboardFocus 事件添加处理程序并检查 InputManager.Current.MostRecentInputDevice 是否为 KeyboardDevice 来完成相同的操作。

您可能想要添加附加的依赖属性,以便您仍然可以使用触发器,例如 IsFocusVisualVisible。如果最后一个输入设备是键盘,则可以在 GotKeyboardFocus 处理程序中将其设置为 true,并在 LostKeyboardFocus 的处理程序中将其设置为 false。

By default, FrameworkElement checks what the last input device was in an override for OnGotKeyboardFocus. If the last input device was a keyboard, then it shows the FocusVisualStyle.

You can accomplish the same thing by adding a handler for the GotKeyboardFocus event and checking if InputManager.Current.MostRecentInputDevice is KeyboardDevice.

You'd probably want to add an attached dependency property so you can still use a Trigger, say IsFocusVisualVisible. You'd set it to true in your GotKeyboardFocus handler, if the last input device was the keyboard, and set to false in a handler for LostKeyboardFocus.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文