Edit

Share via


How to: Add a Watermark to a TextBox

The following example shows how to aid usability of a TextBox by displaying an explanatory background image inside of the TextBox until the user inputs text, at which point the image is removed. In addition, the background image is restored again if the user removes their input. See illustration below.

A TextBox with a background image

Note

The reason a background image is used in this example rather then simply manipulating the Text property of TextBox, is that a background image will not interfere with data binding.

Example

The following XAML demonstrates the following:

<Window x:Class="watermark.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <ImageBrush x:Key="watermark" ImageSource="textboxbackground.gif" AlignmentX="Left" Stretch="None" />
    </Window.Resources>
    <StackPanel>
        <TextBox Name="myTextBox" TextChanged="OnTextBoxTextChanged" Width="200" Background="{StaticResource watermark}" />
    </StackPanel>
</Window>

The following code handles the TextBox.TextChanged event:

private void OnTextBoxTextChanged(object sender, TextChangedEventArgs e)
{
    if (sender is TextBox box)
    {
        if (string.IsNullOrEmpty(box.Text))
            box.Background = (ImageBrush)FindResource("watermark");
        else
            box.Background = null;
    }
}
Private Sub OnTextBoxTextChanged(sender As Object, e As TextChangedEventArgs)
    If TypeOf sender Is TextBox Then
        Dim box As TextBox = DirectCast(sender, TextBox)

        If String.IsNullOrEmpty(box.Text) Then
            box.Background = DirectCast(FindResource("watermark"), ImageBrush)
        Else
            box.Background = Nothing
        End If
    End If
End Sub

See also