How to add a watermark to a textbox using WPF

Some time ago I had to implement a search box which filtered a result set in a DataGrid. It was a pretty straight forward exercise. However, it took some time to find a good example and change it into what I needed.

Basically, what needs to be done is to add a TextBlock and a TextBox to your WPF window. Place the TextBlock on top of the TextBox and then dynamically set the visibility of the TextBlock based on if there is text in the textbox.

<Window x:Class="WpfWaterMark.MainWindow"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   Title="TextBox Watermark" Height="184" Width="311">
   <Window.Resources>
    <SolidColorBrush x:Key="WatermarkForeground"
       Color="LightGray" />
    <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
   </Window.Resources>
   <Grid >
    <TextBlock Margin="16,43,132,83" Text="Search..."
       Foreground="{StaticResource WatermarkForeground}"
       Visibility="{Binding ElementName=textBoxSearch,
       Path=Text.IsEmpty,
       Converter={StaticResource BooleanToVisibilityConverter}}" />
    <TextBox Name="textBoxSearch"
       Background="Transparent" Margin="8,40,73,83" />
   </Grid>
</Window>

I used the built in BooleanToVisibilityConverter to provide me the true or false value. I bound the Visibility property of the TextBlock to the textBoxSearch control and the Path property is the Pseudo if statement.

Download the source