How to make a placeholder in a Textbox?

Asked

Viewed 1,818 times

5

How can I simulate a placeholder using WPF?

Something like the input HTML where you click in the field it adds the text and when you change it returns the text?


Remembering that it is in WPF, because in Windows Forms I know only that the way I do, I can not do in WPF.

1 answer

3


You can adapt directly into WPF code, remembering that this style should be inserted after the declaration of your Window, or may be applied to Application.Resources Application.xaml of the project.

That is the result!
Resultado

 <Window.Resources>
   <Style x: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>

Mode of use:

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

To read more about styles, click here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.