Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

have a TextBox item (MyTextBox) on a TabItem control. I have code that looks as follows:

MyTextBox.Focus();
Keyboard.Focus(MyTextBox);

When I run this code through the debugger I see the following after the lines are executed:

MyTextBox.IsFocused = true
MyTextBox.IsKeyboardFocused = false

Can anyone tell me why the textbox isn't receiving keyboard focus? It's just a standard TextBox control that is enabled.

like image 558
Randy Minder Avatar asked Feb 01 '11 21:02

Randy Minder


People also ask

How do I make my keyboard focus?

Understanding Focus When an HTML element is able to handle keyboard input, it is said to have focus. Exactly one element is able to have focus in a time. In most browsers, users can move focus by pressing the Tab key and the Shift + Tab keys.

How do you focus a text box in WPF?

Instead of using a Setter on the TextBox , we'll have to use the FocusManager . The FocusManger controls focus within a specific focus scope. So by setting FocusManager. FocusedElement on our FocusScope, we can acheive focus on a textbox.

What is focus() in c#?

The Focus method returns true if the control successfully received input focus. The control can have the input focus while not displaying any visual cues of having the focus. This behavior is primarily observed by the nonselectable controls listed below, or any controls derived from them.

What is focus WPF?

In WPF there are two main concepts that pertain to focus: keyboard focus and logical focus. Keyboard focus refers to the element that receives keyboard input and logical focus refers to the element in a focus scope that has focus.


1 Answers

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
         }
      )
);
like image 150
Silviu Avatar answered Nov 10 '22 04:11

Silviu