Posted By


glebd on 08/26/10

Tagged


Statistics


Viewed 84 times
Favorited by 1 user(s)

ClickSelectTextBox


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. public class FocusSelectTextBox : TextBox
  2. {
  3. public FocusSelectTextBox()
  4. {
  5. AddHandler(PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(SelectivelyIgnoreMouseButton), true);
  6. AddHandler(GotKeyboardFocusEvent, new RoutedEventHandler(SelectAllText), true);
  7. AddHandler(MouseDoubleClickEvent, new RoutedEventHandler(SelectAllText), true);
  8. }
  9.  
  10. private static void SelectivelyIgnoreMouseButton(object sender, MouseButtonEventArgs e)
  11. {
  12. // Find the TextBox
  13. DependencyObject parent = e.OriginalSource as UIElement;
  14. while (parent != null && !(parent is TextBox))
  15. parent = VisualTreeHelper.GetParent(parent);
  16.  
  17. if (parent == null) return;
  18. var textBox = (TextBox)parent;
  19. if (textBox.IsKeyboardFocusWithin) return;
  20. // If the text box is not yet focussed, give it the focus and
  21. // stop further processing of this click event.
  22. textBox.Focus();
  23. e.Handled = true;
  24. }
  25.  
  26. private static void SelectAllText(object sender, RoutedEventArgs e)
  27. {
  28. var textBox = e.OriginalSource as TextBox;
  29. if (textBox != null)
  30. textBox.SelectAll();
  31. }
  32. }

URL: http://stackoverflow.com/questions/660554/how-to-automatically-select-all-text-on-focus-in-wpf-textbox/661224#661224

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.