WPF 中的可聚焦面板
我需要在 WPF 中使面板可聚焦,以便它像任何其他可聚焦控件一样捕获键盘事件:
- 用户在面板内单击以使其聚焦于
- 任何
KeyDown
或KeyUp
如果单击面板外的另一个可聚焦元素,则在面板级别引发事件 - ,面板将失去焦点
我在面板和 myPanel.Focus()< 上试验了
FocusManager.IsFocusScope="True"
/code> 返回 true
但面板 KeyUp 事件处理程序仍然没有被调用。
我错过了什么吗?
I need to make a Panel focusable in WPF, so that it captures keyboard events just as any other focusable control:
- The user clicks inside the Panel to give it focus
- any
KeyDown
orKeyUp
event is raised at panel level - if another focusable element outside the panel is clicked, the panel loses focus
I experimented FocusManager.IsFocusScope="True"
on the Panel and myPanel.Focus()
returns true
but the Panel KeyUp event handler still isn't called.
Am I missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
经过更多调查,面板拥有键盘焦点并保持它,直到按下箭头键或 TAB(这会开始焦点循环)。
我刚刚使用“e.Handled = true;”为
KeyDown
事件添加了一个处理程序现在一切正常。总而言之,要拥有一个可聚焦的面板:
FocusManager.IsFocusScope="True"
添加到面板中,最后使用
myPanel.Focus();
为其提供焦点。After more investigation, the Panel has the keyboard focus and keeps it until an arrow key or TAB is pressed (which starts the focus cycling).
I just added a handler for the
KeyDown
event with `e.Handled = true;' and now everything works correctly.To sum it up, to have a focusable Panel:
FocusManager.IsFocusScope="True"
to the PanelFinally give it the focus with
myPanel.Focus();
.如果您的面板不包含任何子元素,即使使用
FocusManager.IsFocusScope="True"
也不会触发 GotFocus 事件。面板并非设计用于接受键盘输入或焦点。相反,大多数时候(例如,如果子元素是 Button 控件)FocusManager.IsFocusScope="True"
甚至会耗尽 KeyUp/KeyDown 事件。您的控件和面板都不会触发该事件。If your panel does not contain any child elements, even using
FocusManager.IsFocusScope="True"
will not fire the GotFocus event. Panel are not designed to take keyboard input or focus. Instead, most of the times (like if the child element is a Button control)FocusManager.IsFocusScope="True"
will even eat up the KeyUp/KeyDown events. The event will not be fired for neither your control nor your panel.