I want to create a TextBox, which would have a gray "default" text appear in it, if it's
a) empty
b) has lost focus
when the user enters the text box, the gray "default" text should dissappear.
I've tried to do this using ControlTemplate.Triggers
, but I can't seem to find HasFocus
property.
What is the best way to do this 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With