Comment sélectionner automatiquement tout le texte sur le focus dans WPF TextBox?

Si j’appelle SelectAll partir d’un GotFocus événements GotFocus , cela ne fonctionne pas avec la souris – la sélection disparaît dès que la souris est relâchée.

EDIT: Les gens aiment la réponse de Donnelle, je vais essayer d’expliquer pourquoi je ne l’ai pas aimé autant que la réponse acceptée.

  • C’est plus complexe, alors que la réponse acceptée fait la même chose d’une manière plus simple.
  • La facilité d’utilisation de la réponse acceptée est meilleure. Lorsque vous cliquez au milieu du texte, le texte est désélectionné lorsque vous relâchez la souris, ce qui vous permet de commencer à éditer instantanément. Si vous souhaitez toujours tout sélectionner, appuyez à nouveau sur le bouton pour le désélectionner. En suivant la recette de Donelle, si je clique au milieu du texte, je dois cliquer une seconde fois pour pouvoir modifier. Si je clique quelque part dans le texte par rapport à l’extérieur du texte, cela signifie probablement que je veux commencer à éditer au lieu de tout remplacer.

Je ne sais pas pourquoi il perd la sélection dans l’événement GotFocus.

Mais une solution consiste à faire la sélection sur les événements GotKeyboardFocus et GotMouseCapture. De cette façon, cela fonctionnera toujours.

Nous l’avons donc le premier clic sélectionne tout, et un autre clic va au curseur (notre application est conçue pour être utilisée sur des tablettes avec des stylos).

Vous pourriez le trouver utile.

 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 réponse de Donnelle fonctionne le mieux, mais avoir à dériver une nouvelle classe pour l’utiliser est une douleur.

Au lieu de le faire, j’inscris les gestionnaires des gestionnaires dans App.xaml.cs pour toutes les zones de texte dans l’application. Cela me permet d’utiliser la réponse de Donnelle avec le contrôle TextBox standard.

Ajoutez les méthodes suivantes à votre 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(); } } 

C’est plutôt vieux, mais je vais quand même afficher ma réponse.
J’ai choisi une partie de la réponse de Donnelle (sans le double-clic) car je pense que cela crée le moins d’étonnement chez les utilisateurs. Cependant, comme gcores, je n’aime pas la nécessité de créer une classe dérivée. Mais je n’aime pas non plus la méthode gcores “on Startup …”. Et j’ai besoin de cela sur une base “généralement mais pas toujours”.

Je l’ai implémenté comme une propriété de dépendance attachée afin que je puisse définir SelectTextOnFocus.Active=True dans xaml. Je trouve cette façon la plus agréable.

 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(); } } [AttachedPropertyBrowsableForChildrenAtsortingbute(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); } } } 

Pour ma fonctionnalité “générale mais pas toujours”, je définis cette propriété sur True dans un style TextBox (global). De cette façon, “sélectionner le texte” est toujours “activé”, mais je suis capable de le désactiver sur une base par zone de texte.

Voici les comportements de mélange qui implémentent la solution de réponse pour votre commodité:

Un pour attacher à une seule zone de texte:

 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; } } } 

Et un pour attacher à la racine d’un conteneur contenant plusieurs zones de texte:

 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(); } } 

Voici une très bonne solution très simple sur MSDN :

  

Voici le code derrière:

 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(); } } } 

Bien que ce soit une vieille question, je viens d’avoir ce problème mais je l’ai résolu en utilisant un comportement attaché, plutôt qu’un comportement d’expression comme dans la réponse de Sergey. Cela signifie que je n’ai pas besoin d’une dépendance sur System.Windows.Interactivity dans le SDK Blend:

 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(); } } 

Vous pouvez ensuite l’utiliser dans votre XAML comme ceci:

  

J’ai blogué à ce sujet ici .

Je pense que cela fonctionne 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 vous souhaitez l’implémenter comme méthode d’extension:

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

Et dans votre événement GotFocus:

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

J’ai découvert la solution ci-dessus car il y a plusieurs mois, je cherchais un moyen de mettre l’accent sur un UIElement donné. J’ai découvert le code ci-dessous quelque part (le crédit est donné par la présente) et cela fonctionne bien. Je le poste bien qu’il ne soit pas directement lié à la question du PO, car il illustre le même schéma d’utilisation de Dispatcher pour travailler avec 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); } 

Je n’ai trouvé aucune des réponses présentées ici qui imitent un textbox Windows standard. Par exemple, essayez de cliquer dans l’espace blanc entre le dernier caractère de la zone de texte et le côté droit de la zone de texte. La plupart des solutions ici sélectionneront toujours l’intégralité du contenu, ce qui rend très difficile l’ajout de texte à une zone de texte.

La réponse que je présente ici se comporte mieux à cet égard. C’est un comportement (il nécessite donc l’assembly System.Windows.Interactivity du Blend SDK ). Il pourrait également être réécrit en utilisant les propriétés attachées.

 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; } } 

Ceci est basé sur le code que j’ai trouvé ici .

dans le fichier App.xaml

    

Dans le fichier App.xaml.cs

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

Avec ce code, vous accédez à toutes les TextBox de votre application.

Cette simple implémentation fonctionne parfaitement pour moi:

 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; } } 

Pour l’appliquer à toutes les TextBox , placez le code suivant après InitializeComponent();

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

Tiré d’ ici :

Enregistrez le gestionnaire d’événement global dans le fichier App.xaml.cs:

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

Ensuite, le gestionnaire est aussi simple que:

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

J’ai une réponse légèrement simplifiée pour cela (avec juste l’événement PreviewMouseLeftButtonDown) qui semble imiter les fonctionnalités habituelles d’un navigateur:

Dans xaml vous avez une zone de texte dites:

  

Dans codebehind:

 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(); } } 

Pour ceux qui s’intéressent à l’approche de Donnelle / Groky, mais veulent un clic à la droite du dernier caractère (mais toujours dans la zone de texte) pour placer le curseur à la fin du texte saisi, j’ai trouvé cette solution:

  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(); } 

La méthode GetRoundedCharacterIndexFromPoint a été extraite de cette publication.

  #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 

Essayez cette méthode d’extension pour append le comportement souhaité à tout contrôle TextBox. Je ne l’ai pas encore beaucoup testé, mais cela semble répondre à mes besoins.

 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(); } } } } 

J’ai cherché beaucoup pour la solution, j’ai trouvé quelques solutions à sélectionner Mais, le problème est que lorsque nous faisons un clic droit et coupons / copions après avoir sélectionné une partie du texte de la zone de texte, il sélectionne même la partie du texte sélectionnée. Pour résoudre ce problème, voici la solution. Ajoutez simplement le code ci-dessous dans l’événement de sélection du clavier. Cela a fonctionné pour moi.

 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(); } 

J’ai utilisé la réponse de Nils mais je suis devenu plus 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); } [AttachedPropertyBrowsableForChildrenAtsortingbute(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); } } 

In XAML, you can use like one of these:

         

J’ai eu le même problème. In VB.Net it works easy that way:

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 sortingggers into a style.

Then it comes down to this

   

et ça

  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. This is working perfectly for me. 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.

J’espère que ça aide.

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

J’espère que cela aide.

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(); } 

HOU LA LA! After reading all the above I find myself overwhelmed and confused. I took what I thought I learned in this post and sortinged 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…