I would like to set the focus of a WPF TextBox
from codebehind (not the TextBox
's codebehind, but some parent control) and select all text in the TextBox
from the TextBox
s codebehind when it receives that focus.
I focus the TextBox
like this:
var scope = FocusManager.GetFocusScope(txt);
FocusManager.SetFocusedElement(scope, txt);
and listen to the event in the TextBox
like this in the TextBox
s codebehind:
AddHandler(GotFocusEvent, new RoutedEventHandler(SelectAllText), true);
and try to select the text like this:
private static void SelectAllText(object sender, RoutedEventArgs e)
{
var textBox = e.OriginalSource as TextBox;
if (textBox != null)
textBox.SelectAll();
}
But the text doesn't get selected. How can I modify this to work as I'd like it to?
You will have to set Keyboard
focus on the TextBox
before selecting the text
Example:
private static void SelectAllText(object sender, RoutedEventArgs e)
{
var textBox = e.OriginalSource as TextBox;
if (textBox != null)
{
Keyboard.Focus(textBox);
textBox.SelectAll();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With