WPF - Why isn't Keyboard.Focus() working?

When you try to set Focus to an element besides the things enumerated above by our coleague, you must also know that WPF does not allow cross threaded operations.

In some cases this exception is not raised like in the Focus method call case. What I've done to fix this issue is to call all the code that involves Keyboards focus in an action.

This action is ran inside the control dispatcher to make sure that my code is not being executed from another thread than the UI thread (e.g. timer event or an event raised from another thread):

[UIElement].Dispatcher.BeginInvoke(
      new Action(
         delegate{
             /// put your Focus code here
         }
      )
);

MyTextBox.IsKeyboardFocused is false because you are looking at it under debugger and the keyboard focus is probably in your Visual Studio... Try debugging focus without breakpoints (e.g. Debug.Write or trace brakepoints) to see actual values of MyTextBox.IsKeyboardFocused in runtime.

Also notice that Focus() method returns boolean value that indicates whether focus was successfully set. Does it return False in your case? If yes, I would suggest stepping into Focus() method in order to find out what is wrong.


3 important properties must be true: IsVisible="True", Focusable="True". IsEnabled="True".

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

http://msdn.microsoft.com/en-us/library/system.windows.uielement.focus.aspx