Bart's Smarts

Smart .NET, Silverlight, and SharePoint Development.

Posts Tagged ‘Silverlight’

Silverlight TextBox: Select text when focused with tab Key

Posted by sapientcoder on July 15, 2009

A common request I receive from Silverlight application users is for all the text within a TextBox to be selected when the control gains focus because of the tab key and not because of clicking on it with the mouse. In other words, if a user clicks the control with the mouse, they want the insertion cursor to appear where it normally would, but if they’re quickly tabbing through fields entering data, they want whatever value is in the field to be selected so it can be easily cleared out.

This can actually be accomplished pretty easily using attached properties in Silverlight and will yield XAML such as this:


<df:DataForm Name="myDataForm"
                   AutoEdit="True"
                   AutoGenerateFields="False"
                   CommandButtonsVisibility="None"
                   ui:TextBoxSelection.SelectAllOnTabFocus="True">

    <df:DataForm.EditTemplate>
        <DataTemplate>
            <StackPanel>
                <df:DataField>
                    <TextBox Text="{Binding Field1, Mode=TwoWay}" />
                </df:DataField>

                <df:DataField>
                    <TextBox Text="{Binding Field2, Mode=TwoWay}" />
                </df:DataField>
            </StackPanel>
        </DataTemplate>
    </df:DataForm.EditTemplate>

</df:DataForm>

Note the use of the TextBoxSelection.SelectAllOnTabFocus property. In this case, I’m attaching it to a DataForm, but it could be attached to any DependencyObject of type FrameworkElement. In this example, the TextBoxes bound to “Field1″ and “Field2″ will select all of their text when the user causes them to get focus by hitting the tab key. If I had wanted to have only the second TextBox exhibit this behavior, I could remove the line that sets the SelectAllOnTabFocus property from the DataForm tag and place it inside of the second TextBox tag.

Here’s the code for the TextBoxSelection class:


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

namespace MySilverlightApp.UI
{
    public class TextBoxSelection
    {
        public static readonly DependencyProperty SelectAllOnTabFocusProperty =
            DependencyProperty.RegisterAttached(
                "SelectAllOnTabFocus",
                typeof(bool),
                typeof(TextBoxSelection),
                new PropertyMetadata(OnSelectAllOnTabFocusPropertyChanged)
            );

        public static bool GetSelectAllOnTabFocus(DependencyObject obj)
        {
            return (bool)obj.GetValue(SelectAllOnTabFocusProperty);
        }

        public static void SetSelectAllOnTabFocus(DependencyObject obj, bool selectAllOnTabFocus)
        {
            obj.SetValue(SelectAllOnTabFocusProperty, selectAllOnTabFocus);
        }

        private static void OnSelectAllOnTabFocusPropertyChanged(
            DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            FrameworkElement fe = (FrameworkElement)obj;

            if ((bool)e.NewValue)
            {
                fe.KeyUp += control_KeyUp;
            }
            else
            {
                fe.KeyUp -= control_KeyUp;
            }
        }

        private static void control_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Tab)
            {
                object element = FocusManager.GetFocusedElement();
                if (element != null && element is TextBox)
                {
                    ((TextBox)element).SelectAll();
                }
            }
        }
    }
}

That’s it. Now you’ve got a reusable way to apply this behavior anywhere where TextBoxes are used in your application.

UPDATE: I put together a small sample application that you can download to see a working example of this solution. The sample application was created in Visual Studio 2008 and requires the Silverlight 3 SDK.

Posted in Silverlight 3 | Tagged: , | 3 Comments »