Create Watermark / HintText Textbox in WPF / XAML

In this example we shall see, how we can add watermark / hint text to wpf controls like textbox. In modern UI based application it is being used very extensively. A snapshot of its usage is added below.

As we can see it eliminates the need of labels against each input controls.
To achieve the same behavior in WPF, we will use System.Windows.Media.VisualBrush. In this visual brush we will add textblock,  and make stylish as we want for the application.

 XAML Code

        <VisualBrush x:Key="LoginHint" Stretch="None" AlignmentX="Left" AlignmentY="Top" >
                    <TranslateTransform X="5" Y="7" />
                    <Grid HorizontalAlignment="Left">
                      <TextBlock FontFamily="SEGOEWP"  FontSize="10"   FontWeight="Normal"
                           HorizontalAlignment="Left" VerticalAlignment="Center"                                     Foreground="Gray" FontStyle="Italic" Opacity="1"                                          Text="Enter Username"/>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        <Label x:Name="lblUserName" Content="User Name" Grid.Column="0"                              VerticalAlignment="Top" Margin="5"/>
        <TextBox x:Name="waterMarkTextBox" Width="100" Height="25" Grid.Column="1" 
        VerticalAlignment="Top" HorizontalAlignment="Left" Margin="5">
             <Style TargetType="{x:Type TextBox}">
               <Setter Property="Background" Value="Transparent"/>
                   <DataTrigger Binding="{Binding ElementName=waterMarkTextBox,Path=Text}"                     Value="" >
                      <Setter Property="Background" Value="{StaticResource LoginHint}"/>


Empty Textbox with Watermark Text

Textbox with inserted value from user