I'm trying to select all the text when the focus is done with the Tab key. But I'm not able to find the right solution. Now I'm using the GotFocusEvent but now when i click with the mouse it raises the event.
The code that I'm using now is:
EventManager.RegisterClassHandler(typeof(System.Windows.Controls.TextBox), System.Windows.Controls.TextBox.GotKeyboardFocusEvent, new RoutedEventHandler(SelectAllText));
void SelectAllText(object sender, RoutedEventArgs e)
{
var textBox = sender as System.Windows.Controls.TextBox;
if (textBox != null)
if (!textBox.IsReadOnly)
textBox.SelectAll();
}
Referencing this answer
Textbox SelectAll on tab but not mouse click
What you have can be modified to...
EventManager.RegisterClassHandler(typeof(System.Windows.Controls.TextBox), System.Windows.Controls.TextBox.GotKeyboardFocusEvent, new KeyboardFocusChangedEventHandler(OnGotKeyboardFocus));
void OnGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
var textBox = sender as System.Windows.Controls.TextBox;
if (textBox != null && !textBox.IsReadOnly && e.KeyboardDevice.IsKeyDown(Key.Tab))
textBox.SelectAll();
}
You should also take notice of the details about clearing the selection on LostKeyboardFocus
Use MouseButtonState
as below:
void SelectAllText(object sender, RoutedEventArgs e)
{
if (Mouse.LeftButton == MouseButtonState.Released)
{
var textBox = sender as System.Windows.Controls.TextBox;
if (textBox != null)
if (!textBox.IsReadOnly)
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