WPF Label – Click and Focus on Element

WPF applications have labels and controls but, unfortunately, they don’t integrate together as easily as in HTML. In HTML you rely on the id and for attributes to bind them together. Then when the label is clicked the control gets focus. So in that environment labels serve to identify the control, as well as aid in accessing it. Sometimes it’s easier to click on a label then the form element itself, such as with checkboxes and radios.

I wanted to achieve the same effect in WPF. I accomplished this by creating and referencing my own customized label. The new label inherits all the features of a traditional label but also includes a few others.

To begin, we create the class. Out of the box a WPF label will stretch horizontally to fill the entire area it resides in. By setting the HorizontalAlignment it collapses it down to the width of its content. This can be overridden in the xaml. We then give the element focus based on a mousedown event.

I also have a bit of code just for textboxes. Once focused the cursor will be placed at the front of any text. You can use the code below to move the cursor to the end, or select the text.
Next, we need to reference the new label in the xaml. To do this we must declare a namespace in the Window object then reference it on each call to the control. The example shows EnvelopePrinting. Replace that with the name of your namespace. We also use Target attribute and Binding call to link the two elements together.