3

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'.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Julio Motol
  • 763
  • 5
  • 22
  • Does this answer your question? [Watermark / hint text / placeholder TextBox](https://stackoverflow.com/questions/833943/watermark-hint-text-placeholder-textbox) – StayOnTarget Jun 24 '21 at 12:28

1 Answers1

3

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

Jim
  • 2,974
  • 2
  • 19
  • 29
  • @JulioMotol you're welcome, although its the meaning that you accept and/or upvote the answer if it's correct and been helpful :-) – Jim Nov 23 '16 at 03:17
  • but the thing is, it is placed on a grid with a blue background on it and now, the text box also has a blue bg since its on alpha. – Julio Motol Nov 23 '16 at 04:14
  • @JulioMotol yup you have to play around and tweak things to your specific needs :-) – Jim Nov 23 '16 at 04:35