Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

wpf

xaml

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?

like image 679
Arsen Zahray Avatar asked May 03 '12 09:05

Arsen Zahray


1 Answers

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

like image 190
Steve Greatrex Avatar answered Sep 27 '22 21:09

Steve Greatrex