¿Cómo seleccionar automáticamente todo el texto en el foco en WPF TextBox?

Si llamo a SelectAll desde un controlador de eventos GotFocus , no funciona con el mouse; la selección desaparece tan pronto como se suelta el mouse.

EDITAR: A la gente le gusta la respuesta de Donnelle, intentaré explicar por qué no me gustó tanto como la respuesta aceptada.

  • Es más complejo, mientras que la respuesta aceptada hace lo mismo de una manera más simple.
  • La usabilidad de la respuesta aceptada es mejor. Cuando hace clic en el medio del texto, el texto se deselecciona cuando suelta el mouse, lo que le permite comenzar a editar al instante, y si aún desea seleccionar todo, simplemente presione el botón nuevamente y esta vez no se deseleccionará al soltarlo. Siguiendo la receta de Donelle, si hago clic en el medio del texto, tengo que hacer clic por segunda vez para poder editar. Si hago clic en algún lugar dentro del texto versus fuera del texto, esto probablemente signifique que quiero comenzar a editar en lugar de sobrescribir todo.

No sé por qué pierde la selección en el evento GotFocus.

Pero una solución es hacer la selección en los eventos GotKeyboardFocus y GotMouseCapture. De esa manera siempre funcionará.

Lo tenemos así que el primer clic selecciona todo, y otro clic va al cursor (nuestra aplicación está diseñada para usar en tabletas con bolígrafos).

Tu podrias encontrar esto útil.

 public class ClickSelectTextBox : TextBox { public ClickSelectTextBox() { AddHandler(PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(SelectivelyIgnoreMouseButton), true); AddHandler(GotKeyboardFocusEvent, new RoutedEventHandler(SelectAllText), true); AddHandler(MouseDoubleClickEvent, new RoutedEventHandler(SelectAllText), true); } private static void SelectivelyIgnoreMouseButton(object sender, MouseButtonEventArgs e) { // Find the TextBox DependencyObject parent = e.OriginalSource as UIElement; while (parent != null && !(parent is TextBox)) parent = VisualTreeHelper.GetParent(parent); if (parent != null) { var textBox = (TextBox)parent; if (!textBox.IsKeyboardFocusWithin) { // If the text box is not yet focussed, give it the focus and // stop further processing of this click event. textBox.Focus(); e.Handled = true; } } } private static void SelectAllText(object sender, RoutedEventArgs e) { var textBox = e.OriginalSource as TextBox; if (textBox != null) textBox.SelectAll(); } } 

La respuesta de Donnelle funciona mejor, pero tener que derivar una nueva clase para usarla es un dolor.

En lugar de hacer eso, registro a los manejadores los manejadores en App.xaml.cs para todos los TextBoxes en la aplicación. Esto me permite usar una respuesta de Donnelle con control estándar de TextBox.

Agregue los siguientes métodos a su App.xaml.cs:

 public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { // Select the text in a TextBox when it receives focus. EventManager.RegisterClassHandler(typeof(TextBox), TextBox.PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(SelectivelyIgnoreMouseButton)); EventManager.RegisterClassHandler(typeof(TextBox), TextBox.GotKeyboardFocusEvent, new RoutedEventHandler(SelectAllText)); EventManager.RegisterClassHandler(typeof(TextBox), TextBox.MouseDoubleClickEvent, new RoutedEventHandler(SelectAllText)); base.OnStartup(e); } void SelectivelyIgnoreMouseButton(object sender, MouseButtonEventArgs e) { // Find the TextBox DependencyObject parent = e.OriginalSource as UIElement; while (parent != null && !(parent is TextBox)) parent = VisualTreeHelper.GetParent(parent); if (parent != null) { var textBox = (TextBox)parent; if (!textBox.IsKeyboardFocusWithin) { // If the text box is not yet focused, give it the focus and // stop further processing of this click event. textBox.Focus(); e.Handled = true; } } } void SelectAllText(object sender, RoutedEventArgs e) { var textBox = e.OriginalSource as TextBox; if (textBox != null) textBox.SelectAll(); } } 

Esto es bastante viejo, pero mostraré mi respuesta de todos modos.
Elegí parte de la respuesta de Donnelle (salté el doble clic) ya que creo que esto crea el menor asombro en los usuarios. Sin embargo, como gcores no me gusta la necesidad de crear una clase derivada. Pero tampoco me gusta el método de gcores “en el inicio …”. Y necesito esto en una base “general, pero no siempre”.

Lo he implementado como una propiedad de dependencia adjunta, por lo que puedo establecer SelectTextOnFocus.Active=True en xaml. Encuentro de esta manera el más agradable.

 namespace foo.styles.behaviour { using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; public class SelectTextOnFocus : DependencyObject { public static readonly DependencyProperty ActiveProperty = DependencyProperty.RegisterAttached( "Active", typeof(bool), typeof(SelectTextOnFocus), new PropertyMetadata(false, ActivePropertyChanged)); private static void ActivePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is TextBox) { TextBox textBox = d as TextBox; if ((e.NewValue as bool?).GetValueOrDefault(false)) { textBox.GotKeyboardFocus += OnKeyboardFocusSelectText; textBox.PreviewMouseLeftButtonDown += OnMouseLeftButtonDown; } else { textBox.GotKeyboardFocus -= OnKeyboardFocusSelectText; textBox.PreviewMouseLeftButtonDown -= OnMouseLeftButtonDown; } } } private static void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { DependencyObject dependencyObject = GetParentFromVisualTree(e.OriginalSource); if (dependencyObject == null) { return; } var textBox = (TextBox)dependencyObject; if (!textBox.IsKeyboardFocusWithin) { textBox.Focus(); e.Handled = true; } } private static DependencyObject GetParentFromVisualTree(object source) { DependencyObject parent = source as UIElement; while (parent != null && !(parent is TextBox)) { parent = VisualTreeHelper.GetParent(parent); } return parent; } private static void OnKeyboardFocusSelectText(object sender, KeyboardFocusChangedEventArgs e) { TextBox textBox = e.OriginalSource as TextBox; if (textBox != null) { textBox.SelectAll(); } } [AttachedPropertyBrowsableForChildrenAttribute(IncludeDescendants = false)] [AttachedPropertyBrowsableForType(typeof(TextBox))] public static bool GetActive(DependencyObject @object) { return (bool) @object.GetValue(ActiveProperty); } public static void SetActive(DependencyObject @object, bool value) { @object.SetValue(ActiveProperty, value); } } } 

Para mi característica “general, pero no siempre”, configuré esta Propiedad en True en un TextBox-Style (global). De esta forma, “seleccionar el texto” siempre está “activado”, pero puedo deshabilitarlo por cuadro de texto.

Estos son los comportamientos de Blend implementando la solución de respuesta para su conveniencia:

Uno para adjuntar a un solo TextBox:

 public class SelectAllTextOnFocusBehavior : Behavior { protected override void OnAttached() { base.OnAttached(); AssociatedObject.GotKeyboardFocus += AssociatedObjectGotKeyboardFocus; AssociatedObject.GotMouseCapture += AssociatedObjectGotMouseCapture; AssociatedObject.PreviewMouseLeftButtonDown += AssociatedObjectPreviewMouseLeftButtonDown; } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.GotKeyboardFocus -= AssociatedObjectGotKeyboardFocus; AssociatedObject.GotMouseCapture -= AssociatedObjectGotMouseCapture; AssociatedObject.PreviewMouseLeftButtonDown -= AssociatedObjectPreviewMouseLeftButtonDown; } private void AssociatedObjectGotKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e) { AssociatedObject.SelectAll(); } private void AssociatedObjectGotMouseCapture(object sender, System.Windows.Input.MouseEventArgs e) { AssociatedObject.SelectAll(); } private void AssociatedObjectPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if(!AssociatedObject.IsKeyboardFocusWithin) { AssociatedObject.Focus(); e.Handled = true; } } } 

Y uno para adjuntar a la raíz de un contenedor que contiene múltiples TextBox’es:

 public class SelectAllTextOnFocusMultiBehavior : Behavior { protected override void OnAttached() { base.OnAttached(); AssociatedObject.GotKeyboardFocus += HandleKeyboardFocus; AssociatedObject.GotMouseCapture += HandleMouseCapture; } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.GotKeyboardFocus -= HandleKeyboardFocus; AssociatedObject.GotMouseCapture -= HandleMouseCapture; } private static void HandleKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e) { var txt = e.NewFocus as TextBox; if (txt != null) txt.SelectAll(); } private static void HandleMouseCapture(object sender, System.Windows.Input.MouseEventArgs e) { var txt = e.OriginalSource as TextBox; if (txt != null) txt.SelectAll(); } } 

Aquí hay una muy buena solución muy simple en MSDN :

  

Aquí está el código detrás:

 private void SelectAddress(object sender, RoutedEventArgs e) { TextBox tb = (sender as TextBox); if (tb != null) { tb.SelectAll(); } } private void SelectivelyIgnoreMouseButton(object sender, MouseButtonEventArgs e) { TextBox tb = (sender as TextBox); if (tb != null) { if (!tb.IsKeyboardFocusWithin) { e.Handled = true; tb.Focus(); } } } 

Aunque esta es una vieja pregunta, acabo de tener este problema pero lo resolví usando un comportamiento adjunto, en lugar de un comportamiento de expresión como en la respuesta de Sergey. Esto significa que no necesito una dependencia de System.Windows.Interactivity en Blend SDK:

 public class TextBoxBehavior { public static bool GetSelectAllTextOnFocus(TextBox textBox) { return (bool)textBox.GetValue(SelectAllTextOnFocusProperty); } public static void SetSelectAllTextOnFocus(TextBox textBox, bool value) { textBox.SetValue(SelectAllTextOnFocusProperty, value); } public static readonly DependencyProperty SelectAllTextOnFocusProperty = DependencyProperty.RegisterAttached( "SelectAllTextOnFocus", typeof (bool), typeof (TextBoxBehavior), new UIPropertyMetadata(false, OnSelectAllTextOnFocusChanged)); private static void OnSelectAllTextOnFocusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var textBox = d as TextBox; if (textBox == null) return; if (e.NewValue is bool == false) return; if ((bool) e.NewValue) { textBox.GotFocus += SelectAll; textBox.PreviewMouseDown += IgnoreMouseButton; } else { textBox.GotFocus -= SelectAll; textBox.PreviewMouseDown -= IgnoreMouseButton; } } private static void SelectAll(object sender, RoutedEventArgs e) { var textBox = e.OriginalSource as TextBox; if (textBox == null) return; textBox.SelectAll(); } private static void IgnoreMouseButton(object sender, System.Windows.Input.MouseButtonEventArgs e) { var textBox = sender as TextBox; if (textBox == null || textBox.IsKeyboardFocusWithin) return; e.Handled = true; textBox.Focus(); } } 

Luego puede usarlo en su XAML de esta manera:

  

Blogé sobre esto aquí .

Creo que esto funciona bien:

 private void ValueText_GotFocus(object sender, RoutedEventArgs e) { TextBox tb = (TextBox)e.OriginalSource; tb.Dispatcher.BeginInvoke( new Action(delegate { tb.SelectAll(); }), System.Windows.Threading.DispatcherPriority.Input); } 

Si desea implementarlo como un método de extensión:

 public static void SelectAllText(this System.Windows.Controls.TextBox tb) { tb.Dispatcher.BeginInvoke( new Action(delegate { tb.SelectAll(); }), System.Windows.Threading.DispatcherPriority.Input); } 

Y en tu evento GotFocus:

 private void ValueText_GotFocus(object sender, RoutedEventArgs e) { TextBox tb = (TextBox)e.OriginalSource; tb.SelectAllText(); } 

Descubrí la solución anterior porque hace varios meses estaba buscando una forma de enfocar un UIElement dado. Descubrí el código a continuación en algún lado (se da crédito por el presente) y funciona bien. Lo publico a pesar de que no está directamente relacionado con la pregunta del OP porque muestra el mismo patrón de uso de Dispatcher para trabajar con un UIElement.

 // Sets focus to uiElement public static void DelayedFocus(this UIElement uiElement) { uiElement.Dispatcher.BeginInvoke( new Action(delegate { uiElement.Focusable = true; uiElement.Focus(); Keyboard.Focus(uiElement); }), DispatcherPriority.Render); } 

No he encontrado ninguna de las respuestas que aquí se presentan imitando un cuadro de texto estándar de Windows. Por ejemplo, intente hacer clic en el espacio en blanco entre el último carácter del cuadro de texto y el lado derecho del cuadro de texto. La mayoría de las soluciones aquí siempre seleccionarán todo el contenido, lo que hace que sea muy difícil agregar texto a un cuadro de texto.

La respuesta que presento aquí se comporta mejor a este respecto. Es un comportamiento (por lo que requiere el ensamblado System.Windows.Interactivity del Blend SDK ). También podría reescribirse utilizando propiedades adjuntas.

 public sealed class SelectAllTextOnFocusBehavior : Behavior { protected override void OnAttached() { base.OnAttached(); AssociatedObject.PreviewMouseLeftButtonDown += AssociatedObject_PreviewMouseLeftButtonDown; } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.PreviewMouseLeftButtonDown -= AssociatedObject_PreviewMouseLeftButtonDown; } void AssociatedObject_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { // Find the textbox DependencyObject parent = e.OriginalSource as UIElement; while (parent != null && !(parent is TextBox)) parent = VisualTreeHelper.GetParent(parent); var textBox = parent as TextBox; Debug.Assert(textBox != null); if (textBox.IsFocused) return; textBox.SelectAll(); Keyboard.Focus(textBox); e.Handled = true; } } 

Esto se basa en el código que he encontrado aquí .

en el archivo App.xaml

    

en el archivo App.xaml.cs

 private void TextBox_GotKeyboardFocus(Object sender, KeyboardFocusChangedEventArgs e) { ((TextBox)sender).SelectAll(); } 

Con este código, llegarás a todo el TextBox en tu aplicación.

Esta sencilla implementación funciona perfectamente para mí:

 void TextBox_GotFocus(object sender, RoutedEventArgs e) { ((TextBox) sender).SelectAll(); } void TextBox_PreviewMouseDown(object sender, MouseButtonEventArgs e) { var TextBox = (TextBox) sender; if (!TextBox.IsKeyboardFocusWithin) { TextBox.Focus(); e.Handled = true; } } 

Para aplicarlo a todos los TextBox , ponga el siguiente código después de InitializeComponent();

 EventManager.RegisterClassHandler(typeof(TextBox), TextBox.GotFocusEvent, new RoutedEventHandler(TextBox_GotFocus)); EventManager.RegisterClassHandler(typeof(TextBox), TextBox.PreviewMouseDownEvent, new MouseButtonEventHandler(TextBox_PreviewMouseDown)); 

Tomado desde aquí :

Registre el controlador de eventos global en el archivo App.xaml.cs:

 protected override void OnStartup(StartupEventArgs e) { EventManager.RegisterClassHandler(typeof(TextBox),TextBox.GotFocusEvent, new RoutedEventHandler(TextBox_GotFocus)); base.OnStartup(e); } 

Entonces el controlador es tan simple como:

 private void TextBox_GotFocus(object sender, RoutedEventArgs e) { (sender as TextBox).SelectAll(); } 

Tengo una respuesta ligeramente simplificada para esto (con solo el evento PreviewMouseLeftButtonDown) que parece imitar la funcionalidad habitual de un navegador:

En xaml tienes un cuadro de texto que dice:

  

En código subyacente:

 private void SelectAll(object sender, MouseButtonEventArgs e) { TextBox tb = (sender as TextBox); if (tb == null) { return; } if (!tb.IsKeyboardFocusWithin) { tb.SelectAll(); e.Handled = true; tb.Focus(); } } 

Para aquellos interesados ​​en el enfoque de Donnelle / Groky, pero quiero un clic a la derecha del último caracter (pero aún dentro del TextBox) para colocar el símbolo de intercalación al final del texto ingresado, he encontrado esta solución:

  int GetRoundedCharacterIndexFromPoint(TextBox textBox, Point clickedPoint) { int position = textBox.GetCharacterIndexFromPoint(clickedPoint, true); // Check if the clicked point is actually closer to the next character // or if it exceeds the righmost character in the textbox // (in this case return increase the position by 1) Rect charLeftEdge = textBox.GetRectFromCharacterIndex(position, false); Rect charRightEdge = textBox.GetRectFromCharacterIndex(position, true); double charWidth = charRightEdge.X - charLeftEdge.X; if (clickedPoint.X + charWidth / 2 > charLeftEdge.X + charWidth) position++; return position; } void SelectivelyIgnoreMouseButton(object sender, MouseButtonEventArgs e) { // Find the TextBox DependencyObject parent = e.OriginalSource as UIElement; while (parent != null && !(parent is TextBox)) parent = VisualTreeHelper.GetParent(parent); if (parent != null) { var textBox = (TextBox)parent; if (!textBox.IsKeyboardFocusWithin) { // If the text box is not yet focused, give it the focus and // stop further processing of this click event. textBox.Focus(); e.Handled = true; } else { int pos = GetRoundedCharacterIndexFromPoint(textBox, e.GetPosition(textBox)); textBox.CaretIndex = pos; } } } void SelectAllText(object sender, RoutedEventArgs e) { var textBox = e.OriginalSource as TextBox; if (textBox != null) textBox.SelectAll(); } 

El método GetRoundedCharacterIndexFromPoint se tomó de esta publicación.

  #region TextBoxIDCard selection private bool textBoxIDCardGotFocus = false; private void TextBoxIDCard_GotFocus(object sender, RoutedEventArgs e) { this.TextBoxIDCard.SelectAll(); } private void TextBoxIDCard_LostFocus(object sender, RoutedEventArgs e) { textBoxIDCardGotFocus = false; } private void TextBoxIDCard_PreviewMouseDown(object sender, MouseButtonEventArgs e) { if (textBoxIDCardGotFocus == false) { e.Handled = true; this.TextBoxIDCard.Focus(); textBoxIDCardGotFocus = true; } } #endregion 

Pruebe este método de extensión para agregar el comportamiento deseado a cualquier control TextBox. Todavía no lo he probado exhaustivamente, pero parece satisfacer mis necesidades.

 public static class TextBoxExtensions { public static void SetupSelectAllOnGotFocus(this TextBox source) { source.GotFocus += SelectAll; source.PreviewMouseLeftButtonDown += SelectivelyIgnoreMouseButton; } private static void SelectAll(object sender, RoutedEventArgs e) { var textBox = e.OriginalSource as TextBox; if (textBox != null) textBox.SelectAll(); } private static void SelectivelyIgnoreMouseButton(object sender, MouseButtonEventArgs e) { var textBox = (sender as TextBox); if (textBox != null) { if (!textBox.IsKeyboardFocusWithin) { e.Handled = true; textBox.Focus(); } } } } 

Busqué mucho la solución, encontré algunas soluciones para seleccionar Pero, el problema es cuando hacemos clic derecho y hacemos corte / copia después de seleccionar parte del texto del cuadro de texto, selecciona todo, incluso yo seleccioné parte del texto. Solucionar esto aquí es la solución. Simplemente agregue el siguiente código en el evento de selección del teclado. Esto funcionó para mí.

 private static void SelectContentsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is TextBox) { TextBox textBox = d as TextBox; if ((e.NewValue as bool?).GetValueOrDefault(false)) { textBox.GotKeyboardFocus += OnKeyboardFocusSelectText; } else { textBox.GotKeyboardFocus -= OnKeyboardFocusSelectText; } } } private static void OnKeyboardFocusSelectText(object sender, KeyboardFocusChangedEventArgs e) { if (e.KeyboardDevice.IsKeyDown(Key.Tab)) ((TextBox)sender).SelectAll(); } 

He usado la respuesta de Nils, pero me he convertido en más flexible.

 public enum SelectAllMode { ///  /// On first focus, it selects all then leave off textbox and doesn't check again ///  OnFirstFocusThenLeaveOff = 0, ///  /// On first focus, it selects all then never selects ///  OnFirstFocusThenNever = 1, ///  /// Selects all on every focus ///  OnEveryFocus = 2, ///  /// Never selects text (WPF's default attitude) ///  Never = 4, } public partial class TextBox : DependencyObject { public static readonly DependencyProperty SelectAllModeProperty = DependencyProperty.RegisterAttached( "SelectAllMode", typeof(SelectAllMode?), typeof(TextBox), new PropertyMetadata(SelectAllModePropertyChanged)); private static void SelectAllModePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is System.Windows.Controls.TextBox) { var textBox = d as System.Windows.Controls.TextBox; if (e.NewValue != null) { textBox.GotKeyboardFocus += OnKeyboardFocusSelectText; textBox.PreviewMouseLeftButtonDown += OnMouseLeftButtonDown; } else { textBox.GotKeyboardFocus -= OnKeyboardFocusSelectText; textBox.PreviewMouseLeftButtonDown -= OnMouseLeftButtonDown; } } } private static void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { DependencyObject dependencyObject = GetParentFromVisualTree(e.OriginalSource); if (dependencyObject == null) return; var textBox = (System.Windows.Controls.TextBox)dependencyObject; if (!textBox.IsKeyboardFocusWithin) { textBox.Focus(); e.Handled = true; } } private static DependencyObject GetParentFromVisualTree(object source) { DependencyObject parent = source as UIElement; while (parent != null && !(parent is System.Windows.Controls.TextBox)) { parent = VisualTreeHelper.GetParent(parent); } return parent; } private static void OnKeyboardFocusSelectText(object sender, KeyboardFocusChangedEventArgs e) { var textBox = e.OriginalSource as System.Windows.Controls.TextBox; if (textBox == null) return; var selectAllMode = GetSelectAllMode(textBox); if (selectAllMode == SelectAllMode.Never) { textBox.SelectionStart = 0; textBox.SelectionLength = 0; } else textBox.SelectAll(); if (selectAllMode == SelectAllMode.OnFirstFocusThenNever) SetSelectAllMode(textBox, SelectAllMode.Never); else if (selectAllMode == SelectAllMode.OnFirstFocusThenLeaveOff) SetSelectAllMode(textBox, null); } [AttachedPropertyBrowsableForChildrenAttribute(IncludeDescendants = false)] [AttachedPropertyBrowsableForType(typeof(System.Windows.Controls.TextBox))] public static SelectAllMode? GetSelectAllMode(DependencyObject @object) { return (SelectAllMode)@object.GetValue(SelectAllModeProperty); } public static void SetSelectAllMode(DependencyObject @object, SelectAllMode? value) { @object.SetValue(SelectAllModeProperty, value); } } 

En XAML, puede usar uno de estos:

         

Tuve el mismo problema En VB.Net funciona de esa manera:

VB XAML:

  

Codehind:

 Private Sub txtFilterText_GotFocus(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles txtFilterText.GotFocus Me.Dispatcher.BeginInvoke(Sub() txtFilterText.SelectAll() End Sub, DispatcherPriority.ApplicationIdle, Nothing) End Sub 

C# (thanks to ViRuSTriNiTy)

 private delegate void TextBoxSelectAllDelegate(object sender); private void TextBoxSelectAll(object sender) { (sender as System.Windows.Controls.TextBox).SelectAll(); } private void MyTextBox_GotFocus(object sender, System.Windows.RoutedEventArgs e) { TextBoxSelectAllDelegate d = TextBoxSelectAll; this.Dispatcher.BeginInvoke(d, System.Windows.Threading.DispatcherPriority.ApplicationIdle, sender); } 

I realize this is very old, but here is my solution which is based on the expressions/microsoft interactivity and interactions name spaces.

First, I followed the instructions at this link to place interactivity triggers into a style.

Then it comes down to this

   

y esto

  public void TextBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { TextBox tb = e.Source as TextBox; if((tb != null) && (tb.IsKeyboardFocusWithin == false)) { tb.Focus(); e.Handled = true; } } 

In my case, I have a user control where the text boxes are that has a code-behind. The code-behind has the handler function. I gave my user control a name in xaml, and I am using that name for the element. Esto está funcionando perfectamente para mí. Simply apply the style to any textbox where you would like to have all the text selected when you click in the textbox.

The first CallMethodAction calls the text box’s SelectAll function when the GotKeyboardFocus event on the textbox fires.

Espero que esto ayude.

This is by far the simplest solution.

Add a global handler to the application (App.xaml.cs) and done. You are going to need only a few lines of code.

 protected override void OnStartup(StartupEventArgs e) { EventManager.RegisterClassHandler(typeof(TextBox), TextBox.GotFocusEvent, new RoutedEventHandler(TextBox_GotFocus)); base.OnStartup(e); } 

So use the EventManager class to register a global event handler against a type (TextBox). The actual handler is dead simple:

 private void TextBox_GotFocus(object sender, RoutedEventArgs e) { (sender as TextBox).SelectAll(); } 

Check here: WPF TextBox SelectAll on Focus

Espero eso ayude.

This seems to work well for me. It’s basically a recap of some earlier posts. I just put this into my MainWindow.xaml.cs file in the constructor. I create two handlers, one for keyboard, and one for the mouse, and funnel both events into the same function, HandleGotFocusEvent , which is defined right after the constructor in the same file.

 public MainWindow() { InitializeComponent(); EventManager.RegisterClassHandler(typeof(TextBox), UIElement.GotKeyboardFocusEvent, new RoutedEventHandler(HandleGotFocusEvent), true); EventManager.RegisterClassHandler(typeof(TextBox), UIElement.GotMouseCaptureEvent, new RoutedEventHandler(HandleGotFocusEvent), true); } private void HandleGotFocusEvent(object sender, RoutedEventArgs e) { if (sender is TextBox) (sender as TextBox).SelectAll(); } 

An easy way to override the mouseDown and select all after doubleclick is:

 public class DoubleClickTextBox: TextBox { public override void EndInit() { base.EndInit(); } protected override void OnMouseEnter(System.Windows.Input.MouseEventArgs e) { base.OnMouseEnter(e); this.Cursor = Cursors.Arrow; } protected override void OnMouseDown(System.Windows.Input.MouseButtonEventArgs e) { } protected override void OnMouseDoubleClick(System.Windows.Input.MouseButtonEventArgs e) { base.OnMouseDown(e); this.SelectAll(); } } 

Try putting this in the constructor of whatever control is housing your textbox:

 Loaded += (sender, e) => { MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); myTextBox.SelectAll(); } 

Sergei.

After googling and testing, I’ve found a simple solution that worked for me.

You need to add an event handler to the “Loaded” event of your container window:

  private void yourwindow_Loaded(object sender, RoutedEventArgs e) { EventManager.RegisterClassHandler(typeof(TextBox), TextBox.PreviewMouseLeftButtonDownEvent, new RoutedEventHandler(SelectivelyIgnoreMouseButton)); } 

Next, you have to create the handler to the referenced RoutedEventHandler in previous code:

  private void SelectivelyIgnoreMouseButton(object sender, RoutedEventArgs e) { TextBox tb = (sender as TextBox); if (tb != null) { if (!tb.IsKeyboardFocusWithin) { e.Handled = true; tb.Focus(); } } } 

Now, you can add the SelectAll() command on GotFocus event handlers to any TextBox controls separately:

  private void myTextBox_GotFocus(object sender, RoutedEventArgs e) { (sender as TextBox).SelectAll(); } 

Your text now is selected on focus!

Adapted from Dr. WPF solution, MSDN Forums

Here is the C# version of the answer posted by @Nasenbaer

 private delegate void TextBoxSelectAllDelegate(object sender); private void TextBoxSelectAll(object sender) { (sender as System.Windows.Controls.TextBox).SelectAll(); } private void MyTextBox_GotFocus(object sender, System.Windows.RoutedEventArgs e) { TextBoxSelectAllDelegate d = TextBoxSelectAll; this.Dispatcher.BeginInvoke(d, System.Windows.Threading.DispatcherPriority.ApplicationIdle, sender); } 

whereas MyTextBox_GotFocus is the event handler assigned to the GotFocus event of MyTextBox .

I have tested all of them but only the following worked out:

  protected override void OnStartup(StartupEventArgs e) { EventManager.RegisterClassHandler(typeof(TextBox), UIElement.PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(SelectivelyHandleMouseButton), true); EventManager.RegisterClassHandler(typeof(TextBox), UIElement.GotKeyboardFocusEvent, new RoutedEventHandler(SelectAllText), true); EventManager.RegisterClassHandler(typeof(TextBox), UIElement.GotFocusEvent, new RoutedEventHandler(GotFocus), true); } private static void SelectivelyHandleMouseButton(object sender, MouseButtonEventArgs e) { var textbox = (sender as TextBox); if (textbox != null) { int hc = textbox.GetHashCode(); if (hc == LastHashCode) { if (e.OriginalSource.GetType().Name == "TextBoxView") { e.Handled = true; textbox.Focus(); LastHashCode = -1; } } } if (textbox != null) textbox.Focus(); } private static void SelectAllText(object sender, RoutedEventArgs e) { var textBox = e.OriginalSource as TextBox; if (textBox != null) textBox.SelectAll(); } private static int LastHashCode; private static void GotFocus(object sender, RoutedEventArgs e) { var textBox = e.OriginalSource as TextBox; if (textBox != null) LastHashCode = textBox.GetHashCode(); } 

¡GUAUU! After reading all the above I find myself overwhelmed and confused. I took what I thought I learned in this post and tried something completely different. To select the text in a textbox when it gets focus I use this:

 private void TextField_GotFocus(object sender, RoutedEventArgs e) { TextBox tb = (sender as Textbox); if(tb != null) { e.Handled = true; tb.Focus(); tb.SelectAll(); } } 

Set the GotFocus property of the textbox to this method.

Running the application and clicking once in the textbox highlights everything already in the textbox.

If indeed, the objective is to select the text when the user clicks in the textbox, this seems simple and involves a whole lot less code. Just saying…