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"
   Title="TextBox Watermark" Height="184" Width="311">
    <SolidColorBrush x:Key="WatermarkForeground"
       Color="LightGray" />
    <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
   <Grid >
    <TextBlock Margin="16,43,132,83" Text="Search..."
       Foreground="{StaticResource WatermarkForeground}"
       Visibility="{Binding ElementName=textBoxSearch,
       Converter={StaticResource BooleanToVisibilityConverter}}" />
    <TextBox Name="textBoxSearch"
       Background="Transparent" Margin="8,40,73,83" />

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