A minor annoyance of mine is that there is no way to wire up a standard Silverlight TextBox to select its text when it receives the keyboard focus; either via a mouse click or a tab key.

And since users are accustomed to web apps, browsers, and desktop applications that offer the the convenience of selecting textbox text  upon focus, I wanted that behavior in my Silverlight applications.   So to satisfy user expectations as a matter of consistency, I wrote a very simple derived class, TextBoxEx, that will offer this functionality.  The TextBoxEx class derives from TextBox, and can be referenced in XAML for any and all of your TextBox’s.  There are no methods to call.  It just listens for Focus events and selects it own text.  Very simple.

Usage is as follows:

  • In XAML, reference the assembly where you implement the TextBoxEx class listed below, and add as many TextBoxEx elements as you need.  The example below uses data binding to display a username.
<UserControl x:Class="MyApp.MainPage"
	xmlns="http://schemas.microsoft.com/client/2007"     
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     
	xmlns:c="clr-namespace:ClassLibrary;assembly=ClassLibrary"  
>  
.     
.     
.     
<c:TextBoxEx Text="{Binding User.Name, Mode=TwoWay}" Width="120" />

The code below has been tested and used with Silverlight 3 and Silverlight 4.

using System.Windows;
using System.Windows.Controls;

namespace ClassLibrary
{
	// This TextBox derived class selects all text when it receives focus
	public class TextBoxEx : TextBox
	{
		public TextBoxEx()
		{
			base.GotFocus += OnGotFocus;
		}

		private void OnGotFocus(object sender, RoutedEventArgs e)
		{
			base.SelectAll();
		}
	}
}