Advertisement
lerthe61

SelectAllTextBoxBehavior

Feb 17th, 2016
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.51 KB | None | 0 0
  1.    public static class SelectAllTextBoxBehavior
  2.     {
  3.          public static readonly DependencyProperty IsEnabledProperty =
  4.             DependencyProperty.RegisterAttached(
  5.                 "IsEnabled",
  6.                 typeof(bool),
  7.                 typeof(SelectAllTextBoxBehavior),
  8.                 new UIPropertyMetadata(false, OnIsEnabledChanged));
  9.  
  10.         public static bool GetIsEnabled(DependencyObject dependencyObject)
  11.         {
  12.             return (bool)dependencyObject.GetValue(IsEnabledProperty);
  13.         }
  14.  
  15.         public static void SetIsEnabled(DependencyObject dependencyObject, object value)
  16.         {
  17.             dependencyObject.SetValue(IsEnabledProperty, value);
  18.         }
  19.  
  20.         private static void OnIsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  21.         {
  22.             var textBox = d as TextBox;
  23.             if (textBox == null) return;
  24.  
  25.             if ((bool) e.NewValue == true)
  26.             {
  27.                 textBox.GotFocus += TextBoxOnGotFocus;
  28.             }
  29.             else
  30.             {
  31.                 textBox.GotFocus -= TextBoxOnGotFocus;
  32.             }
  33.         }
  34.  
  35.         private static void TextBoxOnGotFocus(object sender, RoutedEventArgs routedEventArgs)
  36.         {
  37.             var senderBox = sender as TextBox;
  38.             if (senderBox == null) return;
  39.  
  40.             // select all if text property contain text
  41.             if (senderBox.Text.Length > 0)
  42.             {
  43.                 senderBox.SelectAll();
  44.             }
  45.         }
  46.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement