I would like to add a watermark to a textbox, while using the MVVM design pattern.
After browsing several hours I have found a solution to my problem - but my solution doesn't work!
The following code is placed in a UserControl, where the textbox should have a watermark saying "Insert Fields.." - or something like it. The watermark disappers when the user types something in the textbox. But I only see an empty textbox; no watermark is visible.
<TextBox x:Name="txtFields" Height="23" TextWrapping="Wrap" Background="#FFCBEECD" AcceptsReturn="True" >
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding AddFieldCommand}"></KeyBinding>
</TextBox.InputBindings>
</TextBox>
<!--Watermark for TextBox-->
<TextBlock IsHitTestVisible="False" Text="Insert Fields.." VerticalAlignment="Center" HorizontalAlignment="Left" Margin="10,0,0,0" Foreground="DarkGray">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding Text, ElementName=txtFields}" Value="">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
Does see why this code doesn't work?
Thanks,
SOLUTION:
<Grid>
<TextBox x:Name="txtMethods" Height="23" TextWrapping="Wrap" Text="Insert Methods" Background="#FFCBEECD" AcceptsReturn="True">
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding AddMethodCommand}"></KeyBinding>
</TextBox.InputBindings>
</TextBox>
<TextBlock IsHitTestVisible="False" Text="Insert Methods.." 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=txtMethods}" Value="">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Grid>
This seems to do the trick for me: