wpf设置焦点的问题

时间:2010-10-11 14:52:39

标签: c# wpf events focus setfocus

您好 我无法将注意力集中在控制之父上。我有一个放在画布上的控件。 如果我单击该控件,我需要在画布上设置焦点以处理一些键盘事件。 尽管事实上我试图像那样设置焦点

 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


        }

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

3 个答案:

答案 0 :(得分:12)

确保Canvas的FocusableIsEnabled都设置为true。没有它,Focus()将失败。来自Focus() docs:

  

要成为焦点,Focusable和IsEnabled必须都是真的。

此外,由于您在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);
 }

答案 1 :(得分:0)

使用FocusManager将画布设置为焦点范围。这里有一个很好的例子:Can't set focus to a child of UserControl

答案 2 :(得分:-3)

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