views:

32

answers:

1

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.

A: 

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);
 }
Reed Copsey
I set these properties to true but my events still do not fire. I override method OnGotFocus to see if this event fires and OnGotFocus fires. However keyboards event don't
george
@george: Is Focus() returning true?
Reed Copsey
Yes it returned true
george
Sorry OnGotFocus event doesn't fire. EDIT Sometimes OnGotFocus is fired and sometimes is not
george
@george: See my edit... it may help.
Reed Copsey
Works fine :) Could You tell me why you call base.OnPreviewMouseDown(e); as last method ?
george
@george: You can do it first, if you want. I typically want my code to run prior to other handling code, but it depends on the situation. In this case, if there's anything else subscribe to the handler that checked forcus, it would see your canvas has the focus, not the currently focused object - it might not matter, but it might, too...
Reed Copsey
Thanks again :) I spent like two hours trying to different methods to set a focus :)
george
@george: Glad I could help. Welcome to StackOverflow ;)
Reed Copsey
@george - if Reed's answer helped you (and it certainly sounds like it did), it is customary in Stack Overflow to mark it as the answer and/or upvote it. This will help both his rating on the site, and yours. Just a good habit to get into, right from the beginning.
Wonko the Sane