Posts Tagged 'WPF Controls'

WPF Shadowed TextBox (aka. WPF Watermark TextBox)

This article demonstrates a Shadowed TextBox in WPF.  The initial concept seemed like it would be easy.  I went through about 3 different iterations in order to tackle this situation.  The first two had potential, but both had odd issues that forced me to try different techniques.  The winning solution uses an adorner to decorate the Textbox with a label.

Failed Techniques

Change the Text and Style on Got/Lost Focus

In this technique I would just  change the Text of the Textbox and and the Style whenever the TextBox Got or Lost Focus.  I had used this technique previously in WinForms, but this App that I was building used Drag-and-Drop in the textboxes and the users had expressed the need for this feature.  The issues with Drag-and-Drop using this technique were a nightmare.  This on top of other issues such as Binding caused be to abandon this technique.

Changing the Textboxes Background to a VisualBrush with with a Label

In this technique I would change the background of the TextBox to a VisualBrush that contained a Label on Got/Lost Focus.  This method had some initial pitfalls and work arounds with sizing.  I finally got past that by setting the VisualBrush Stretch=None.  This technique worked great until I went to my DataBound Form.  If a textbox has a value with one record, when you changed records that textboxes background wouldn’t update.  I searched a long time for a method to override to force that update, but no luck.

Winning Technique

Textbox adorned by a Label

View Code Preview:  ShadowedTextBox.cs
Download Source Code: (70.3 KB)

Shadowed TextBox Preview
Shadowed TextBox Preview

This final technique worked great and involves creating and attaching an AdornerLabel to the TextBox.  This version worked with styling, drag-drop, and Binding, right out of the box.  All you need to do to get the Shadowed TextBox working is add the required files and set the Label and LabelStyle of the ShadowedTextBox.