How to select all WPF TextBox text on focus using an Attached Behavior

UPDATE 12/11/2013: Fixed a mistake in the example code; the setter and getter shouldn’t have “Property” in the name.

I have a simple requirement to select all of the text in a WPF TextBox when it receives focus, this lets a user tab through a bunch of TextBoxes and edit the values directly without having to use the mouse.

Although there are a few methods I could use, I thought I’d tackle this using the “Ramora”, or “Attached Behavior” pattern. I always forget the syntax, hence this post.

Implementing an Attached Behavior involves creating a boolean Attached Property to indicate whether the behavior is to be applied, and then implementing the behavior in the property’s change handler, like this:

Which means you can use it like this in XAML:

So as you can see, it’s really quite simple. I hook into the GotFocus event in OnSelectAllTextOnFocusChanged, and call SelectAll where I select all of the TextBox’s text.

I added a further event handler to ensure that mouse clicks within the TextBox didn’t highlight the text when it already had focus but this isn’t essential.

Tagged , , , , , , , , , , , , ,

4 thoughts on “How to select all WPF TextBox text on focus using an Attached Behavior

  1. Tamer says:

    Hello Richard Dutton,
    thanks for this great post. It is exactly the right solution for my application. My question at this point is, if I may use this class for commercial purposes?

    Best regards

Leave a Reply

%d bloggers like this: