C# WPF – How to create Textbox with Placeholder using XAML Code

MiniBytes: In this article we are going to see, how to create create placeholder in a textbox in WPF application using XAML code. This tutorial will be helpful for you to create textbox placeholder which you can use in your C# WPF application. What i am narrating here is the code which was taken from the live projects which i am currently working on.

Microsoft has not released any code or library files to create a placeholder in the C# language using the XAML code. If you want to create a placeholder in textbox then you need to write your own code or you need to create a technique to display your placeholder in your wpf application.

In this article, i am to going to show an XAML code which i will use in every application for my projects to display the placeholder in textbox.

So the placeholder code goes here:

<Style x:Key="placeHolder" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
            <Setter Property="Template">
                    <ControlTemplate TargetType="{x:Type TextBox}">
                            <TextBox Text="{Binding Path=Text,
                                                RelativeSource={RelativeSource TemplatedParent}, 
                                 Panel.ZIndex="2" />
                            <TextBox Text="{TemplateBinding Tag}" Background="{TemplateBinding Background}" Panel.ZIndex="1">
                                    <Style TargetType="{x:Type TextBox}">
                                        <Setter Property="Foreground" Value="Transparent"/>
                                            <DataTrigger Binding="{Binding Path=Text, Source={x:Reference textSource}}" Value="">
                                                <Setter Property="Foreground" Value="Gray"/>
                                                <Setter Property="HorizontalContentAlignment" Value="Left"/>
                                                <Setter Property="VerticalContentAlignment" Value="Center"/>

You can use the above code ina textbox using the following method.

<TextBox x:Name="sample" Style="{StaticResource placeHolder}" Tag="Search here"><TextBox>

Steps to use the above codes:

  1. At first you need to put the styling code inside the windows or usercontrol resources


…..<!– placeholder style code goes here –>



…..<!– placeholder style code goes here –>


2. Next you need to use the style code in the Textbox for styling it. You can give your placeholder text in the tag=”Search”.

Now you can run your application to see the placeholder inside the textbox. Enjoy the code :-).


You may also like...

3 Responses

  1. Gowthami says:

    This is really usefull

  2. kelsey says:

    thanks sir.

  3. Kenin says:

    Thanks for the code

Leave a Reply

Your email address will not be published. Required fields are marked *