WPF 中的可聚焦面板

发布于 2024-08-10 19:07:11 字数 353 浏览 12 评论 0原文

我需要在 WPF 中使面板可聚焦,以便它像任何其他可聚焦控件一样捕获键盘事件:

  • 用户在面板内单击以使其聚焦于
  • 任何 KeyDownKeyUp 如果单击面板外的另一个可聚焦元素,则在面板级别引发事件
  • ,面板将失去焦点

我在面板和 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 or KeyUp 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 技术交流群。

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

发布评论

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

评论(2

雨落□心尘 2024-08-17 19:07:11

经过更多调查,面板拥有键盘焦点并保持它,直到按下箭头键或 TAB(这会开始焦点循环)。

我刚刚使用“e.Handled = true;”为 KeyDown 事件添加了一个处理程序现在一切正常。

总而言之,要拥有一个可聚焦的面板:

  • FocusManager.IsFocusScope="True" 添加到面板中,
  • 以防止失去对箭头和 Tab 键的焦点:
myPanel.KeyDown += new KeyEventHandler(
    委托(对象发送者,KeyEventArgs e)
    {
        if (e.Key == Key.Left ||
            e.Key == Key.Up ||
            e.Key == Key.Right ||
            e.Key == Key.Down ||
            e.Key == Key.Tab)
            e.已处理=真;
    }
);

最后使用 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:

  • add FocusManager.IsFocusScope="True" to the Panel
  • prevent from loosing focus on arrows and Tab key with:
myPanel.KeyDown += new KeyEventHandler(
    delegate(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Left ||
            e.Key == Key.Up ||
            e.Key == Key.Right ||
            e.Key == Key.Down ||
            e.Key == Key.Tab)
            e.Handled = true;
    }
);

Finally give it the focus with myPanel.Focus();.

嗼ふ静 2024-08-17 19:07:11

如果您的面板不包含任何子元素,即使使用 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.

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