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.
<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}"/>
</Grid>
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.
- private void PasswordLostFocus(object sender, RoutedEventArgs e)
- {
- CheckPasswordWatermark();
- }
- public void CheckPasswordWatermark()
- {
- var passwordEmpty = string.IsNullOrEmpty(Password.Password);
- PasswordWatermark.Opacity = passwordEmpty ? 100 : 0;
- Password.Opacity = passwordEmpty ? 0 : 100;
- }
- private void PasswordGotFocus(object sender, RoutedEventArgs e)
- {
- PasswordWatermark.Opacity = 0;
- Password.Opacity = 100;
- }
When populating the PasswordBox, you can call CheckPasswordWatermark() to show/hide the watermark as appropriate.
May 11th, 2011 - 01:04
Good job! You saved me hours of coding. Thx.
October 6th, 2011 - 20:44
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)
October 20th, 2011 - 08:00
It saved me hours. Thanks
December 16th, 2011 - 11:03
Lovely, thank you
January 13th, 2012 - 07:39
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!
May 20th, 2012 - 15:49
Fantastic. Nice, short and very usefull!
January 24th, 2013 - 10:18
Simple and great!
May 20th, 2013 - 06:45
Very nice simple thought,great job keep it up