Im working on a wpf application.How I can add watermark text to the textbox
and passwordbox
?
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>
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.