WPF
TextBox
C#
UI Design
Programming Tips

How to automatically select all text on focus in WPF TextBox?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Selecting all text when a WPF TextBox receives focus is a small UX improvement that makes data entry much faster, especially for forms where users often replace the existing value. The tricky part is that keyboard focus and mouse focus behave differently, so a good solution handles both.

The basic behavior with focus events

The core action is simple: when the TextBox gets keyboard focus, call SelectAll():

csharp
1private void TextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
2{
3    if (sender is TextBox textBox)
4    {
5        textBox.SelectAll();
6    }
7}

If users tab into the field, this works well. The problem shows up with the mouse. A normal mouse click both gives focus and sets the caret, so the selection can be lost immediately unless you intercept the mouse event.

Handle mouse focus correctly

To make the first click focus the box and select the text instead of placing the caret, handle PreviewMouseLeftButtonDown:

csharp
1private void TextBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
2{
3    if (sender is not TextBox textBox)
4    {
5        return;
6    }
7
8    if (!textBox.IsKeyboardFocusWithin)
9    {
10        e.Handled = true;
11        textBox.Focus();
12    }
13}

The key condition is !textBox.IsKeyboardFocusWithin. If the box does not yet have focus, the handler grabs focus on the first click and prevents the default caret placement. After focus is established, the GotKeyboardFocus handler selects the text.

Wired together in XAML, the solution looks like this:

xml
1<TextBox
2    Width="200"
3    Text="Existing value"
4    GotKeyboardFocus="TextBox_GotKeyboardFocus"
5    PreviewMouseLeftButtonDown="TextBox_PreviewMouseLeftButtonDown" />

This is enough for many applications and is easy to understand during maintenance.

A reusable attached behavior

If you need this behavior across many text boxes, an attached property is cleaner than repeating event handlers in every window or user control.

csharp
1using System.Windows;
2using System.Windows.Controls;
3using System.Windows.Input;
4
5public static class TextBoxBehaviors
6{
7    public static readonly DependencyProperty SelectAllOnFocusProperty =
8        DependencyProperty.RegisterAttached(
9            "SelectAllOnFocus",
10            typeof(bool),
11            typeof(TextBoxBehaviors),
12            new UIPropertyMetadata(false, OnSelectAllOnFocusChanged));
13
14    public static bool GetSelectAllOnFocus(DependencyObject obj) =>
15        (bool)obj.GetValue(SelectAllOnFocusProperty);
16
17    public static void SetSelectAllOnFocus(DependencyObject obj, bool value) =>
18        obj.SetValue(SelectAllOnFocusProperty, value);
19
20    private static void OnSelectAllOnFocusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
21    {
22        if (d is not TextBox textBox)
23        {
24            return;
25        }
26
27        if ((bool)e.NewValue)
28        {
29            textBox.GotKeyboardFocus += TextBox_GotKeyboardFocus;
30            textBox.PreviewMouseLeftButtonDown += TextBox_PreviewMouseLeftButtonDown;
31        }
32        else
33        {
34            textBox.GotKeyboardFocus -= TextBox_GotKeyboardFocus;
35            textBox.PreviewMouseLeftButtonDown -= TextBox_PreviewMouseLeftButtonDown;
36        }
37    }
38
39    private static void TextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
40    {
41        ((TextBox)sender).SelectAll();
42    }
43
44    private static void TextBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
45    {
46        var textBox = (TextBox)sender;
47        if (!textBox.IsKeyboardFocusWithin)
48        {
49            e.Handled = true;
50            textBox.Focus();
51        }
52    }
53}

Then enable it in XAML:

xml
1<TextBox
2    Width="200"
3    Text="12345"
4    local:TextBoxBehaviors.SelectAllOnFocus="True" />

This keeps the view logic declarative and avoids repetitive code-behind wiring.

Why GotFocus alone is usually not enough

Many examples on the internet use only GotFocus or GotKeyboardFocus. That works for keyboard navigation, but mouse clicks often still place the caret where the user clicked. The result is inconsistent behavior: tabbing selects all, clicking does not.

That is why the preview mouse event matters. It changes the first click from "place caret here" into "give focus first", which allows the focus handler to own the selection.

Common Pitfalls

The most common mistake is using only GotFocus and then wondering why single-click selection fails. Mouse focus and keyboard focus are not the same interaction path.

Another issue is attaching the preview mouse handler too broadly. If you apply it to read-only or specialized text controls without thinking through the interaction, you may create surprising behavior.

Developers also sometimes reselect text every time the field is clicked, which makes it impossible to place the caret intentionally after the first focus event. The IsKeyboardFocusWithin check prevents that.

Finally, test with tab navigation, mouse clicks, and programmatic focus changes. Good focus behavior should feel consistent across all three.

Summary

  • Call SelectAll() when the TextBox receives keyboard focus.
  • Intercept the first mouse click with PreviewMouseLeftButtonDown so the caret does not override the selection.
  • Use an attached behavior when you want the pattern across many text boxes.
  • 'GotFocus alone is usually not enough for a polished experience.'
  • Guard the mouse logic with IsKeyboardFocusWithin so later clicks still behave naturally.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.