Silverlight / Windows Phone 7 Behavior to enhance Usability of TextBoxes

Yesterday I used an application on my Windows Phone which was very useful. When you gave focus to a TextBox it would immediately select all of the content of the TextBox. Though it’s not difficult to implement I found it very useful, and see it as a productivity enhancement for the users of the application.

The behavior is applied on any TextBox, and will attach to the GotFocus event and on the occurrence of the event it will execute the SelectAll method of the TextBox.

public class SelectAllOnFocusBehavior : Behavior<TextBox>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.GotFocus += GotFocus;
    }

    private void GotFocus(object sender, RoutedEventArgs e)
    {
        AssociatedObject.SelectAll();
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.GotFocus -= GotFocus;
    }
}

 

And using it is really simple. Just like any other Behavior add it to the Interaction.Behaviors collection of the TextBox where you want to apply this behavior.

<TextBox Text="Some content">
    <I:Interaction.Behaviors>
        <Behaviors:SelectAllOnFocusBehavior />
    </I:Interaction.Behaviors>
</TextBox>

 

The result could like like this, after giving focus to the TextBox.

Behavior applied to the TextBox in a Windows Phone application

Gravatar