First of all, I must apologise that it’s been so long since I last blogged. It’s been an insanely busy time for me (and I don’t mean that I’ve been coding with my underpants on my head). As you may be aware, I’m a big fan of Blend behaviours, so I thought that I’d take the time to revisit an old favourite of mine. To that end, I present all the code you’ll need to create a watermarked textbox.
public class WatermarkTextBoxBehavior : Behavior<TextBox>
protected override void OnAttached()
AssociatedObject.LostFocus += new RoutedEventHandler(LostFocus);
AssociatedObject.GotFocus += new RoutedEventHandler(GotFocus);
protected override void OnDetaching()
AssociatedObject.LostFocus -= new RoutedEventHandler(LostFocus);
AssociatedObject.GotFocus -= new RoutedEventHandler(GotFocus);
The code is pretty straightforward. When the textbox receives focus, if it contains just the watermark text, the watermark text is cleared out and the original foreground and background brushes are restored. When the textbox loses focus, if it’s empty, the watermark text is displayed and the watermark fore and background brushes are set. Now, for the clever bit, because we’re updating the textbox text directly, we aren’t going to be updating any underlying binding.