TextBoxBehavior.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. namespace Aitex.Sorter.UI.Controls.Common
  9. {
  10. public class TextBoxBehavior
  11. {
  12. public static bool GetSelectAllTextOnFocus(TextBox textBox)
  13. {
  14. return (bool)textBox.GetValue(SelectAllTextOnFocusProperty);
  15. }
  16. public static void SetSelectAllTextOnFocus(TextBox textBox, bool value)
  17. {
  18. textBox.SetValue(SelectAllTextOnFocusProperty, value);
  19. }
  20. public static readonly DependencyProperty SelectAllTextOnFocusProperty =
  21. DependencyProperty.RegisterAttached(
  22. "SelectAllTextOnFocus",
  23. typeof(bool),
  24. typeof(TextBoxBehavior),
  25. new UIPropertyMetadata(false, OnSelectAllTextOnFocusChanged));
  26. private static void OnSelectAllTextOnFocusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  27. {
  28. var textBox = d as TextBox;
  29. if (textBox == null) return;
  30. if (e.NewValue is bool == false) return;
  31. if ((bool)e.NewValue)
  32. {
  33. textBox.GotFocus += SelectAll;
  34. textBox.PreviewMouseDown += IgnoreMouseButton;
  35. }
  36. else
  37. {
  38. textBox.GotFocus -= SelectAll;
  39. textBox.PreviewMouseDown -= IgnoreMouseButton;
  40. }
  41. }
  42. private static void SelectAll(object sender, RoutedEventArgs e)
  43. {
  44. var textBox = e.OriginalSource as TextBox;
  45. if (textBox == null) return;
  46. textBox.SelectAll();
  47. }
  48. private static void IgnoreMouseButton(object sender, System.Windows.Input.MouseButtonEventArgs e)
  49. {
  50. var textBox = sender as TextBox;
  51. if (textBox == null || (!textBox.IsReadOnly && textBox.IsKeyboardFocusWithin)) return;
  52. e.Handled = true;
  53. textBox.Focus();
  54. }
  55. }
  56. }