Feb
7
2010

Watermarked TextBox with an AttachedProperty



Comments available as RSS 2.0

Ever wanted to create a watermark effect for a TextBox in WPF? Most of the tutorials scattered around have either used static text or created a subclass of TextBox. I wanted to use an AttachedProperty instead, and though it took a while to try every possible combination of brackets and bindings I came up with the following to create an AttachedProperty which you can apply in any ResourceDictionary or wherever you keep your Styles.


Watermarks with Attached Properties
Get the code after the jump.

public class WatermarkedTextBox
{
  public static readonly DependencyProperty WatermarkProperty = DependencyProperty.RegisterAttached("Watermark", typeof(string), typeof(WatermarkedTextBox));
 
  public static void SetWatermark(TextBox element, string watermark) {
    element.SetValue(WatermarkProperty, watermark);
  }
 
  public static string GetWatermark(UIElement element) {
    return element.GetValue(WatermarkProperty) as string;
  }
}

You need to include the namespace for whichever assemly contains the AttachedProperty (l49ui in my case).

<Style TargetType="{x:Type TextBoxBase}" x:Key="{x:Type TextBox}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type TextBoxBase}">
        <Grid>
          <ScrollViewer Margin="0" x:Name="PART_ContentHost" Background="Transparent"/>
          <TextBlock x:Name="watermark" Opacity="0.3"
             Text="{Binding (l49ui:WatermarkedTextBox.Watermark),RelativeSource={RelativeSource TemplatedParent}}"
             TextWrapping="Wrap"
             Visibility="Collapsed" />
        </Grid>
        <ControlTemplate.Triggers>
          <MultiTrigger>
            <MultiTrigger.Conditions>
              <Condition Property="IsFocused" Value="False" />
              <Condition Property="TextBox.Text" Value="" />
            </MultiTrigger.Conditions>
            <Setter Property="Visibility" TargetName="watermark" Value="Visible" />
          </MultiTrigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

Comments

Leave a Comment

Login using OpenID or enter your details below to leave a comment.

OpenID
Anonymous


Comment