3

This is for a TextBox control on a login screen, where the TextBox contains the username. I want the TextBox to perform in the following way:

  • When the content is empty the content should be set to "Username".

  • When the TextBox is clicked I want the content to be set to "" i.e; nothing (unless the content has already been edited by the user).

This is a pretty standard feature nowadays, something like this wordpress login (at the top of page). coudn't think of a better example than this I'm afraid :)

So, anyway, I've already done this using a ViewModel and it works well, but I'd like to know if this can be done purely from the XAML end. No business logic is concerned so I think it would be better to do it without the VM.

Metro Smurf
  • 37,266
  • 20
  • 108
  • 140
Drahcir
  • 11,772
  • 24
  • 86
  • 128
  • 1
    possible duplicate of [Watermark TextBox in WPF](http://stackoverflow.com/questions/833943/watermark-textbox-in-wpf) – Robaticus May 21 '12 at 14:55
  • @Robaticus: These answers only show with code logic, I want to be able to do this with pure XAML. – Drahcir May 21 '12 at 15:00
  • I doubt that you're going to be able to do it in "pure xaml." Besides, in the example given, the only code is a visibility converter. There is no business logic or viewmodel in play. – Robaticus May 21 '12 at 15:19
  • Have you tried searching the internet? This stackoverflow post (first in my bing results) seems like it would help [https://stackoverflow.com/questions/833943/watermark-textbox-in-wpf](https://stackoverflow.com/questions/833943/watermark-textbox-in-wpf) – Shawn Kendrot May 21 '12 at 14:56

3 Answers3

4

Pure XAML:

<Grid>
    <TextBox  Width="250"  VerticalAlignment="Center" HorizontalAlignment="Left" x:Name="SearchTermTextBox" Margin="5"/>
    <TextBlock IsHitTestVisible="False" Text="Enter Search Term Here" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="10,0,0,0" Foreground="DarkGray">
        <TextBlock.Style>
            <Style TargetType="{x:Type TextBlock}">
                <Setter Property="Visibility" Value="Collapsed"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Text, ElementName=SearchTermTextBox}" Value="">
                        <Setter Property="Visibility" Value="Visible"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
    </TextBlock>
</Grid>

Taken from: https://stackoverflow.com/a/21672408/4423545

Andrew_STOP_RU_WAR_IN_UA
  • 9,318
  • 5
  • 65
  • 101
1

The Extended WPF Toolkit has a Watermark Textbox that will do just what you're asking in pure XAML. There are other libraries out there as well.

The good thing about using the Extended WPF Toolkit is you can pick it up on Nuget and install and install updates directly through Visual Studio.

Metro Smurf
  • 37,266
  • 20
  • 108
  • 140