Automatically selecting TextBox Text when Focused

Here’s another AttachedProperty from my WPF library that I use a lot. When set on a TextBox, it will select all the text when the TextBox gains keyboard focus.

It is used like this:

<TextBox my:TextBoxHelper.HighlightTextOnFocus="True" />

The actual AttachedProperty defintion looks like this:

public static readonly DependencyProperty HighlightTextOnFocusProperty =
		"HighlightTextOnFocus", typeof(bool), typeof(TextBoxProperties),
		new PropertyMetadata(false, HighlightTextOnFocusPropertyChanged));

[AttachedPropertyBrowsableForChildrenAttribute(IncludeDescendants = false)]
public static bool GetHighlightTextOnFocus(DependencyObject obj)
	return (bool)obj.GetValue(HighlightTextOnFocusProperty);

public static void SetHighlightTextOnFocus(DependencyObject obj, bool value)
	obj.SetValue(HighlightTextOnFocusProperty, value);

private static void HighlightTextOnFocusPropertyChanged(DependencyObject obj,
														DependencyPropertyChangedEventArgs e)
	var sender = obj as UIElement;
	if (obj != null)
		if ((bool)e.NewValue)
			sender.GotKeyboardFocus += OnKeyboardFocusSelectText;
			sender.PreviewMouseLeftButtonDown += OnMouseLeftButtonDownSetFocus;
			sender.GotKeyboardFocus -= OnKeyboardFocusSelectText;
			sender.PreviewMouseLeftButtonDown -= OnMouseLeftButtonDownSetFocus;

private static void OnKeyboardFocusSelectText(object sender, KeyboardFocusChangedEventArgs e)
	var textBox = e.OriginalSource as TextBox;
	if (textBox != null)

private static void OnMouseLeftButtonDownSetFocus(object sender, MouseButtonEventArgs e)
	TextBox tb = VisualTreeHelpers.FindAncestor((DependencyObject)e.OriginalSource);

	if (tb == null)

	if (!tb.IsKeyboardFocusWithin)
		e.Handled = true;

I particularly like using this in editing forms, so that the user can simply select or tab to a TextBox and start typing the new value, rather then selecting the TextBox, erasing the old value, and then typing the new value. It’s one of those little things that makes an application more user-friendly.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

Join 89 other followers

%d bloggers like this: