简体   繁体   中英

How to access focused element programmatically WPF C#

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

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM