wpf设置焦点问题

发布于 2024-09-27 03:29:52 字数 450 浏览 7 评论 0原文

你好 我无法将焦点集中在控制父级上。我有一个放置在画布上的控件。 如果我单击该控件,我需要将焦点设置在画布上才能处理一些键盘事件。 然而,尽管我试图将焦点设置为

 protected override void OnPreviewMouseDown(MouseButtonEventArgs e)
        {
            base.OnPreviewMouseDown(e);
           Canvas designer = VisualTreeHelper.GetParent(this) as Canvas;
          designer.Focus() ;//this doesn't work
           Keyboard.Focus(designer); //this also doesn't work


        }

附加到画布的键盘事件不会触发。

Hi
I'm not able to set focus on parent of control. I have a control which is placed on canvas.
If I click that control I need to set focus on canvas in order to handle some keyboard events.
However despite the fact that I was trying to set focus like that

 protected override void OnPreviewMouseDown(MouseButtonEventArgs e)
        {
            base.OnPreviewMouseDown(e);
           Canvas designer = VisualTreeHelper.GetParent(this) as Canvas;
          designer.Focus() ;//this doesn't work
           Keyboard.Focus(designer); //this also doesn't work


        }

Keyboard events which are attached to canvas don't fire.

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

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

发布评论

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

评论(3

烟雨凡馨 2024-10-04 03:29:52

确保画布具有可聚焦IsEnabled 均设置为 true。否则,Focus() 将失败。来自 Focus() 文档:

要获得焦点,Focusable 和 IsEnabled 都必须为 true。

此外,由于您是在 PreviewMouseDown 事件中执行此操作,因此您可能需要按如下方式重新设计您的方法:

 protected override void OnPreviewMouseDown(MouseButtonEventArgs e)
 {
     Canvas designer = VisualTreeHelper.GetParent(this) as Canvas;
     designer.Focus() ;//this doesn't work
     Keyboard.Focus(designer); //this also doesn't work

     // Just in case something else is changing your focus as a result of a mouse event...
     e.Handled = true;
     base.OnPreviewMouseDown(e);
 }

Make sure that the Canvas has Focusable and IsEnabled both set to true. Without that, Focus() will fail. From Focus() docs:

To be focusable, Focusable and IsEnabled must both be true.

In addition, since you're doing this in a PreviewMouseDown event, you may need to rework your method as follows:

 protected override void OnPreviewMouseDown(MouseButtonEventArgs e)
 {
     Canvas designer = VisualTreeHelper.GetParent(this) as Canvas;
     designer.Focus() ;//this doesn't work
     Keyboard.Focus(designer); //this also doesn't work

     // Just in case something else is changing your focus as a result of a mouse event...
     e.Handled = true;
     base.OnPreviewMouseDown(e);
 }
王权女流氓 2024-10-04 03:29:52

使用 FocusManager 将画布设置为焦点范围。这里有一个很好的示例说明如何执行此操作: 可以' t 将焦点设置到 UserControl 的子级

Use the FocusManager to set the canvas as a focus scope. There is a good example of how to do this here: Can't set focus to a child of UserControl.

逆流 2024-10-04 03:29:52

我使用 My UserControl 的属性:Background="Transparent"。

I use My UserControl with attribute: Background="Transparent".

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