Reputation: 45
Wondering how should I access elements property which does have the focus. I have found the following code to find the focused element :
var focusedControl = FocusManager.GetFocusedElement(this);
This seems to work well, in debug "focusedcontrol" is the right element however I don't know how to access it programmatically. Something like :
focusedControl.Text = "txt";
The reason why I wanna do this - in the same window as the TextBoxes I have several Buttons which form a keypad. After hitting the Button (Focusable = False) I want to get reference to focused TextBox and insert the corresponding digit in TextBox.Text.
Thanks Lukas
Upvotes: 2
Views: 2532
Reputation: 66509
The GetFocusedElement()
method returns IInputElement
, not a TextBox
.
Since FrameworkElement
implements IInputElement
, and Control
(and TextBox
) are derived from FrameworkElement
, you can just cast the result to a TextBox
yourself:
var focusedControl = FocusManager.GetFocusedElement(this);
var tBox = focusedControl as TextBox;
if (tBox != null)
tBox.Text = "txt";
Upvotes: 3