How can I add watermark text to a textbox in wpf?

心已入冬 提交于 2019-12-01 21:06:55
ClosedEyesSeeing

Take a look at this SO Question. The second answer of creating an Attached Property is what I would suggest.

There are also some extended WPF controls that can help: http://wpftoolkit.codeplex.com/wikipage?title=WatermarkTextBox

Edit: Added Extended WPF Toolkit link.

Or you could try this code

<Grid>
    <Grid.Resources>
        <VisualBrush x:Key="LoginHint" Stretch="None" AlignmentX="Left" AlignmentY="Top" >
                <VisualBrush.Transform>
                    <TranslateTransform X="5" Y="7" />
                </VisualBrush.Transform>
                <VisualBrush.Visual>
                    <Grid HorizontalAlignment="Left">
                      <TextBlock FontFamily="SEGOEWP"  FontSize="10"   FontWeight="Normal"
                           HorizontalAlignment="Left" VerticalAlignment="Center"                                     Foreground="Gray" FontStyle="Italic" Opacity="1"                                          Text="Enter Username"/>
                    </Grid>
                </VisualBrush.Visual>
            </VisualBrush>
        </Grid.Resources>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Label x:Name="lblUserName" Content="User Name" Grid.Column="0"                              VerticalAlignment="Top" Margin="5"/>
        <TextBox x:Name="waterMarkTextBox" Width="100" Height="25" Grid.Column="1" 
        VerticalAlignment="Top" HorizontalAlignment="Left" Margin="5">
          <TextBox.Style>
             <Style TargetType="{x:Type TextBox}">
               <Setter Property="Background" Value="Transparent"/>
                 <Style.Triggers>
                   <DataTrigger Binding="{Binding ElementName=waterMarkTextBox,Path=Text}"                     Value="" >
                      <Setter Property="Background" Value="{StaticResource LoginHint}"/>
                   </DataTrigger>
                 </Style.Triggers>
                </Style>
            </TextBox.Style>
        </TextBox>
    </Grid>

MahApps.Metro has a built-in watermark control and it's fairly straightforward to use. It does work with a PasswordBox.

 <AdornerDecorator>
            <PasswordBox Name="password"
                     Width="200"
                     HorizontalAlignment="Right">
                <Controls:TextBoxHelper.Watermark>Password</Controls:TextBoxHelper.Watermark>
            </PasswordBox>
  </AdornerDecorator>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!