Make “default” text to appear in an empty TextBox without focus using XAML

Whilst there is no real benefit in re-inventing the wheel, it might be interesting to see how this can be done. The easiest way to do this (in pure XAML) is to create a ControlTemplate for the TextBox that overlays a TextBlock when it is not focussed and does not contain text:

<ControlTemplate TargetType="TextBox">
<Grid>
    <TextBox Text="{Binding Text, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}, UpdateSourceTrigger=PropertyChanged}" />
    <TextBlock HorizontalAlignment="Center"
                VerticalAlignment="Center"
                Text="Your Prompt Here"
                Margin="5,0,5,0"
                Foreground="#FF808080"
                FontStyle="Italic"
                IsHitTestVisible="False"
                x:Name="UserMessage"
                Visibility="Hidden"/>
</Grid>
<ControlTemplate.Triggers>
    <MultiTrigger>
        <MultiTrigger.Conditions>
            <Condition Property="Text" Value=""/>
            <Condition Property="IsKeyboardFocusWithin" Value="False"/>
            </MultiTrigger.Conditions>
        <Setter Property="Visibility" TargetName="UserMessage" Value="Visible"/>
    </MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>

The MultiTrigger means “set Visibility to Visible if the Text property is empty AND the TextBox does not have keyboard focus”

If you want to make this more reusable then you could create a custom control with this as it’s default template and with a Dependency Property containing the prompt message

Leave a Comment