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 =
	DependencyProperty.RegisterAttached(
		"HighlightTextOnFocus", typeof(bool), typeof(TextBoxProperties),
		new PropertyMetadata(false, HighlightTextOnFocusPropertyChanged));


[AttachedPropertyBrowsableForChildrenAttribute(IncludeDescendants = false)]
[AttachedPropertyBrowsableForType(typeof(TextBox))]
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;
		}
		else
		{
			sender.GotKeyboardFocus -= OnKeyboardFocusSelectText;
			sender.PreviewMouseLeftButtonDown -= OnMouseLeftButtonDownSetFocus;
		}
	}
}

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

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

	if (tb == null)
		return;

	if (!tb.IsKeyboardFocusWithin)
	{
		tb.Focus();
		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:

WordPress.com Logo

You are commenting using your WordPress.com 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

Follow

Get every new post delivered to your Inbox.

Join 101 other followers

%d bloggers like this: