Windows Phone 7 Watermark on PasswordBox

For my textboxes I’ve been using a modified version Johan Danforth’s Watermark behaviour (binding the watermark text to a ViewModel property instead of hardcoding the text), but when I needed to do something similar for a PasswordBox I thought I was stuck.

I’ve come up with an incredibly basic, simple solution that seems to work well. Instead of just having a PasswordBox, I also have a TextBox behind it which I make invisible when the PasswordBox has content, or has focus.  Because the watermark TextBox is behind the PasswordBox, it never gets focus: it is purely visual.

Code Snippet
    <TextBox x:Name="PasswordWatermark" TextWrapping="Wrap" Text="{Binding Labels.password, Mode=OneTime}" Foreground="{StaticResource PhoneTextBoxReadOnlyBrush}" IsHitTestVisible="False"/>
    <PasswordBox x:Name="Password" LostFocus="PasswordLostFocus" Opacity="0" GotFocus="PasswordGotFocus" Password="{Binding Password, Mode=TwoWay}"/>

In the code-behind I hide/show the watermark TextBox and the PasswordBox as appropriate.  Note that I show and hide them by changing their opacity, not by setting their visibility. 

Because the PasswordBox is in front of the the watermark Textbox, when the user clicks in that area he always clicks on the PasswordBox, even if it is invisible.

Code Snippet
  1. private void PasswordLostFocus(object sender, RoutedEventArgs e)
  2. {
  3.     CheckPasswordWatermark();
  4. }
  6. public void CheckPasswordWatermark()
  7. {
  8.     var passwordEmpty = string.IsNullOrEmpty(Password.Password);
  9.     PasswordWatermark.Opacity = passwordEmpty ? 100 : 0;
  10.     Password.Opacity = passwordEmpty ? 0 : 100;
  11. }
  13. private void PasswordGotFocus(object sender, RoutedEventArgs e)
  14. {
  15.     PasswordWatermark.Opacity = 0;
  16.     Password.Opacity = 100;
  17. }

When populating the PasswordBox, you can call CheckPasswordWatermark() to show/hide the watermark as appropriate.

15 thoughts on “Windows Phone 7 Watermark on PasswordBox

  1. Pingback: Tweets that mention Windows Phone 7 Watermark on PasswordBox « Damian's Blog --

  2. Johnc

    This works great for silverlight as well and saved me a lot of time. Thank you for such a simple outside the box solution. (Watermark is such a common UI element these days I don’t know why it isn’t standard on every control)

  3. Josh

    This took me a little bit to figure out, since I am not quite used to developing in C#, but after I sat down and really examined it for a bit, it made perfect sense, and it works brilliantly! Thank you for making such a short, concise, and perfect working script!

  4. kartiikeya

    good work ,but where is watermark text for it ?? tried the code… On Lost focus ..its not displaying password box..and i cant find any watermark text on it..please help..


Leave a Reply to slobo80 Cancel reply

Your email address will not be published. Required fields are marked *