Julio Motol Julio Motol - 15 days ago 8
C# Question

How do I create a textbox hint, simmiliar to SO's search box

I'm creating a login window for a wpf application and for its textbox, what I want to do is the same as how the 'Search Q&A' on the upper right of the Stack Overflow website behaves.

There is a text box containing a text 'Username' and when you focus, the text it will still be displayed, but when you start to type, the text disappear and your input will be displayed. then when you try to erase it back and nothing is in the textbox, it will revert back to the text 'Username'.

Jim Jim
Answer

The term you are looking for is a Textbox Hint

Try this:

<Window.Resources>
    <VisualBrush x:Key="SearchHint" TileMode="None" Stretch="None" AlignmentX="Left">
        <VisualBrush.Transform>
            <TranslateTransform X="5" Y="0" />
        </VisualBrush.Transform>
        <VisualBrush.Visual>
            <Grid>
                <TextBlock FontStyle="Italic" Foreground="Black" Opacity="0.3" Text="Search …"/>
            </Grid>
        </VisualBrush.Visual>
    </VisualBrush>
</Window.Resources>

<StackPanel>
    <TextBox VerticalContentAlignment="Center"  Height="30">
        <TextBox.Style>
            <Style TargetType="TextBox">
                <Style.Triggers>
                    <Trigger Property="Text" Value="">
                        <Setter Property="Background" Value="{StaticResource SearchHint}"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style>
    </TextBox>
</StackPanel>

Result:

enter image description here