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.
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);
 }
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.
I use My UserControl with attribute: Background="Transparent".
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论