A TextBox that selects its text on focus for Silverlight

by Jim McCurdy 28. August 2009 22:36

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

My Photo Jim is always looking for new clients in need of software development expertise.  He is particularly well suited for Silverlight, .NET, ASP.NET, and WPF projects.

Professional Biography

Jim McCurdy operates Face to Face Software, where he works designing, developing, and managing software projects for a variety of clients.

Jim currently specializes in development projects for Silverlight, .NET, ASP.NET, and WPF platforms. One such project is a complete web site using Silverlight, .NET, and C#; a unique financial and lifestyle planning web application at YinYangMoney.com.

Jim has worked in the software industry for as long as he can remember, and has broad expertise in Web, Windows, and systems technologies. Jim has been a team player on many agile development projects throughout his career, and is a founding member at software startups Astral Development and Powerhouse Entertainment.

You can Email Jim at Face to Face Software.


Welcome Readers