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


<Grid>
    <Grid.Resources>
        <VisualBrush x:Key="LoginHint" Stretch="None" AlignmentX="Left" AlignmentY="Top" >
                <VisualBrush.Transform>
                    <TranslateTransform X="5" Y="7" />
                </VisualBrush.Transform>
                <VisualBrush.Visual>
                    <Grid HorizontalAlignment="Left">
                      <TextBlock FontFamily="SEGOEWP"  FontSize="10"   FontWeight="Normal"
                           HorizontalAlignment="Left" VerticalAlignment="Center"                                     Foreground="Gray" FontStyle="Italic" Opacity="1"                                          Text="Enter Username"/>
                    </Grid>
                </VisualBrush.Visual>
            </VisualBrush>
        </Grid.Resources>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <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">
          <TextBox.Style>
             <Style TargetType="{x:Type TextBox}">
               <Setter Property="Background" Value="Transparent"/>
                 <Style.Triggers>
                   <DataTrigger Binding="{Binding ElementName=waterMarkTextBox,Path=Text}"                     Value="" >
                      <Setter Property="Background" Value="{StaticResource LoginHint}"/>
                   </DataTrigger>
                 </Style.Triggers>
                </Style>
            </TextBox.Style>
        </TextBox>
    </Grid>

Output


Empty Textbox with Watermark Text

Textbox with inserted value from user