简体   繁体   中英

Create WPF Watermark in Pure XAML

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 "" ie; 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.

Have you tried searching the internet? This stackoverflow post (first in my bing results) seems like it would help Watermark / hint text / placeholder TextBox in WPF

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM