Ultilmate AutoSelectAll for TextBox and Controls contains TextBox
if you want to have an SelectAll for TextBox or other controls contains TextBox when frist click inside or got focus
us this code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
public class TextBoxHelper { #region AutoSelectOnFocus (ATTACHED) [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Valider les arguments de méthodes publiques", MessageId = "0")] public static bool GetAutoSelectOnFocus(DependencyObject obj) { return (bool)obj.GetValue(AutoSelectOnFocusProperty); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Valider les arguments de méthodes publiques", MessageId = "0")] public static void SetAutoSelectOnFocus(DependencyObject obj, bool value) { obj.SetValue(AutoSelectOnFocusProperty, value); } public static readonly DependencyProperty AutoSelectOnFocusProperty = DependencyProperty.RegisterAttached("AutoSelectOnFocus", typeof(bool), typeof(TextBoxHelper), new PropertyMetadata(false , (ss, ee) => { FrameworkElement fe = ss as FrameworkElement; fe.Loaded += (sss, eee) => { TextBoxBase tb = null; if (fe is TextBoxBase) tb = fe as TextBoxBase; else { tb = GetChildOfType<TextBox>(ss as DependencyObject); } if (tb != null) { tb.GotFocus += (s, e) => tb.SelectAll(); tb.PreviewMouseLeftButtonDown += (s, e) => { if (!tb.IsKeyboardFocusWithin) { tb.Focus(); e.Handled = true; } }; tb.MouseDoubleClick += (s, e) => tb.SelectAll(); } }; } )); #endregion #region STATIC public static T GetChildOfType<T>(DependencyObject depObj) where T : DependencyObject { if (depObj == null) return null; for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) { var child = VisualTreeHelper.GetChild(depObj, i); var result = (child as T) ?? GetChildOfType<T>(child); if (result != null) return result; } return null; } #endregion } |
usage
1 2 3 |
<TextBox Margin="4 1 0 1" Text="sample" helper:TextBoxHelper.AutoSelectOnFocus="true"/> |
Categories: Non classé
Commentaires récents