Come selezionare automaticamente tutto il testo su focus in TextBox WPF?

Se chiamo SelectAll da un gestore di eventi GotFocus , non funziona con il mouse – la selezione scompare non appena il mouse viene rilasciato.

EDIT: Le persone amano la risposta di Donnelle, cercherò di spiegare perché non mi piaceva tanto quanto la risposta accettata.

  • È più complesso, mentre la risposta accettata fa la stessa cosa in un modo più semplice.
  • L’usabilità della risposta accettata è migliore. Quando fai clic nel mezzo del testo, il testo viene deselezionato quando rilasci il mouse permettendoti di iniziare a modificarlo istantaneamente, e se vuoi comunque selezionarlo, premi di nuovo il pulsante e questa volta non verrà deselezionato al momento del rilascio. Seguendo la ricetta di Donelle, se clicco nel mezzo del testo, devo cliccare una seconda volta per poter editare. Se clicco da qualche parte all’interno del testo anziché all’esterno del testo, questo probabilmente significa che voglio iniziare a editare invece di sovrascrivere tutto.

Non so perché perde la selezione nell’evento GotFocus.

Ma una soluzione è fare la selezione sugli eventi GotKeyboardFocus e GotMouseCapture. In questo modo funzionerà sempre.

Abbiamo così il primo clic seleziona tutto, e un altro clic va al cursore (la nostra applicazione è progettata per l’uso su tablet con penne).

Potresti trovarlo 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 risposta di Donnelle funziona meglio, ma dover derivare una nuova class per usarlo è un dolore.

Invece di farlo registro i gestori in App.xaml.cs per tutti i TextBox nell’applicazione. Questo mi consente di utilizzare la risposta di Donnelle con controllo TextBox standard.

Aggiungi i seguenti metodi al tuo 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(); } } 

Questo è piuttosto vecchio, ma visualizzerò comunque la mia risposta.
Ho scelto parte della risposta di Donnelle (ho saltato il doppio clic) perché penso che questo crea il minimo stupore negli utenti. Tuttavia, come gcores, non mi piace la necessità di creare una class derivata. Ma non mi piace il metodo gcores “Startup …”. E ho bisogno di questo in una “generale ma non sempre” – base.

Ho implementato questo come una proprietà dipendenza dipendenza in modo da poter impostare SelectTextOnFocus.Active=True in xaml. Trovo in questo modo il più piacevole.

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

Per la mia caratteristica “generale ma non sempre” imposto questa proprietà su True in uno stile TextBox (globale). In questo modo “selezionare il testo” è sempre “attivo”, ma sono in grado di disabilitarlo su una base per-Textbox.

Ecco i comportamenti di Blend che implementano la soluzione di risposta per la tua convenienza:

Uno per il collegamento a un singolo 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; } } } 

E uno per il collegamento alla radice di un contenitore contenente più TextBox:

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

Ecco una soluzione molto semplice e molto semplice su MSDN :

  

Ecco il codice dietro:

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

Anche se questa è una vecchia domanda, ho appena avuto questo problema ma l’ho risolto usando un comportamento associato, piuttosto che un comportamento di espressione come nella risposta di Sergey. Ciò significa che non ho bisogno di una dipendenza da System.Windows.Interactivity in 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(); } } 

Puoi quindi usarlo nel tuo XAML in questo modo:

  

Ne ho parlato qui .

Penso che questo funzioni bene:

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

Se desideri implementarlo come metodo di estensione:

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

E nel tuo evento GotFocus:

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

Ho scoperto la soluzione sopra perché diversi mesi fa stavo cercando un modo per focalizzare l’attenzione su un determinato UIElement. Ho scoperto il codice qui sotto da qualche parte (il credito è dato qui) e funziona bene. Lo postò anche se non è direttamente correlato alla domanda dell’OP perché dimostra lo stesso schema di utilizzo di Dispatcher per funzionare 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); } 

Ho trovato nessuna delle risposte presentate qui imitare una casella di testo standard di Windows. Ad esempio, prova a fare clic nello spazio bianco tra l’ultimo carattere della casella di testo e il lato destro della casella di testo. La maggior parte delle soluzioni qui selezionerà sempre l’intero contenuto, il che rende molto difficile l’aggiunta di testo a una casella di testo.

La risposta che presento qui si comporta meglio a questo riguardo. È un comportamento (quindi richiede l’assembly System.Windows.Interactivity da Blend SDK ). Potrebbe essere riscritto usando anche le proprietà allegate.

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

Questo è basato sul codice che ho trovato qui .

nel file App.xaml

    

nel file App.xaml.cs

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

Con questo codice raggiungi tutti i TextBox nella tua applicazione.

Questa semplice implementazione funziona perfettamente per me:

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

Per applicarlo a tutti i TextBox , inserisci il seguente codice dopo InitializeComponent();

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

Preso da qui :

Registrare il gestore di eventi globali nel file App.xaml.cs:

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

Quindi il gestore è semplice come:

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

Ho una risposta leggermente semplificata per questo (con solo l’evento PreviewMouseLeftButtonDown) che sembra imitare la solita funzionalità di un browser:

In xaml hai una casella di testo che dice:

  

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

Per coloro che sono interessati all’approccio di Donnelle / Groky, ma vogliono un clic a destra dell’ultimo carattere (ma ancora all’interno del TextBox) per posizionare il cursore alla fine del testo inserito, ho trovato questa soluzione:

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

Il metodo GetRoundedCharacterIndexFromPoint è stato preso da questo post.

  #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 

Prova questo metodo di estensione per aggiungere il comportamento desiderato a qualsiasi controllo TextBox. Non l’ho ancora testato in modo approfondito, ma sembra soddisfare i miei bisogni.

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

Ho cercato molto per la soluzione, ho trovato un paio di soluzioni per selezionare, ma il problema è quando facciamo clic destro e tagliamo / copia dopo aver selezionato parte del testo dalla casella di testo, seleziona tutto anche io ho selezionato parte del testo. Per risolvere questo problema ecco la soluzione. Basta aggiungere il codice seguente nell’evento di selezione della tastiera. Questo ha funzionato per me.

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

Ho usato la risposta di Nils ma convertito in più flessibile.

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

In XAML, puoi utilizzare uno di questi:

         

Ho avuto lo stesso problema. In VB.Net funziona in questo modo:

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

   

e questo

  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. Questo funziona perfettamente per 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.

Spero che aiuti.

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

Spero che sia d’aiuto.

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

WOW! 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…