How to make a placeholder in a TextBox?

4

How can I simulate a placeholder using WPF?

Something similar to the input of the HTML where you click on the field it adds the text and when you change it returns the text?

Remembering it's in WPF, because in Windows forms I know only the way I do it, I can not do it in WPF.

    
asked by anonymous 28.03.2016 / 13:07

1 answer

3

You can adapt directly in the WPF code, remembering that this style must be inserted after the declaration of its Window , or it can be applied in the Application.Resources of the Application.xaml of the project. Here's the result!

<Window.Resources><Stylex:Key="Estilo_Placeholder" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                    <Grid>
                        <TextBox Text="{Binding Path=Text,
                                                RelativeSource={RelativeSource TemplatedParent}, 
                                                Mode=TwoWay,
                                                UpdateSourceTrigger=PropertyChanged}"
                                 x:Name="Texto" 
                                 Background="Transparent" 
                                 Panel.ZIndex="2" />
                        <TextBox Text="{TemplateBinding Tag}" Background="{TemplateBinding Background}" Panel.ZIndex="1">
                            <TextBox.Style>
                                <Style TargetType="{x:Type TextBox}">
                                    <Setter Property="Foreground" Value="Transparent"/>
                                    <Style.Triggers>
                                        <DataTrigger Binding="{Binding Path=Text, Source={x:Reference Texto}}" Value="">
                                            <Setter Property="Foreground" Value="LightGray"/>
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </TextBox.Style>
                        </TextBox>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

How to use:

<TextBox Style="{StaticResource Estilo_Placeholder}" Tag="Seu texto (placeholder)"/>

To read more about styles, click here

    
13.04.2016 / 22:49