Bookmark and Share Share...    Subscribe to this feed Feed   About Christian Moser  


WPF PasswordBox Control

The password box control is a special type of TextBox designed to enter passwords. The typed in characters are replaced by asterisks. Since the password box contains a sensible password it does not allow cut, copy, undo and redo commands.

 
<StackPanel>
      <Label Content="Password:" />
      <PasswordBox x:Name="passwordBox" Width="130" />
</StackPanel>
 
 

Change the password character

To replace the asteriks character by another character, set the PasswordChar property to the character you desire.

 
<PasswordBox x:Name="passwordBox" PasswordChar="*" />
 
 

Limit the length of the password

To limit the length of the password a user can enter set the MaxLength property to the amount of characters you allow.

 
<PasswordBox x:Name="passwordBox" MaxLength="8" />
 
 

Databind the Password Property of a WPF PasswordBox

When you try to databind the password property of a PasswordBox you will recognize that you cannot do data binding on it. The reason for this is, that the password property is not backed by a DependencyProperty.

The reason is databinding passwords is not a good design for security reasons and should be avoided. But sometimes this security is not necessary, then it's only cumbersome that you cannot bind to the password property. In this special cases you can take advantage of the following PasswortBoxHelper.

 
<StackPanel>
    <PasswordBox w:PasswordHelper.Attach="True" 
         w:PasswordHelper.Password="{Binding Text, ElementName=plain, Mode=TwoWay}" 
                 Width="130"/>
    <TextBlock Padding="10,0" x:Name="plain" />
</StackPanel>
 
 

The PasswordHelper is attached to the password box by calling the PasswordHelper.Attach property. The attached property PasswordHelper.Password provides a bindable copy of the original password property of the PasswordBox control.

 
public static class PasswordHelper
{
    public static readonly DependencyProperty PasswordProperty =
        DependencyProperty.RegisterAttached("Password",
        typeof(string), typeof(PasswordHelper),
        new FrameworkPropertyMetadata(string.Empty, OnPasswordPropertyChanged));
 
    public static readonly DependencyProperty AttachProperty =
        DependencyProperty.RegisterAttached("Attach",
        typeof(bool), typeof(PasswordHelper), new PropertyMetadata(false, Attach));
 
    private static readonly DependencyProperty IsUpdatingProperty =
       DependencyProperty.RegisterAttached("IsUpdating", typeof(bool), 
       typeof(PasswordHelper));
 
 
    public static void SetAttach(DependencyObject dp, bool value)
    {
        dp.SetValue(AttachProperty, value);
    }
 
    public static bool GetAttach(DependencyObject dp)
    {
        return (bool)dp.GetValue(AttachProperty);
    }
 
    public static string GetPassword(DependencyObject dp)
    {
        return (string)dp.GetValue(PasswordProperty);
    }
 
    public static void SetPassword(DependencyObject dp, string value)
    {
        dp.SetValue(PasswordProperty, value);
    }
 
    private static bool GetIsUpdating(DependencyObject dp)
    {
        return (bool)dp.GetValue(IsUpdatingProperty);
    }
 
    private static void SetIsUpdating(DependencyObject dp, bool value)
    {
        dp.SetValue(IsUpdatingProperty, value);
    }
 
    private static void OnPasswordPropertyChanged(DependencyObject sender,
        DependencyPropertyChangedEventArgs e)
    {
        PasswordBox passwordBox = sender as PasswordBox;
        passwordBox.PasswordChanged -= PasswordChanged;
 
        if (!(bool)GetIsUpdating(passwordBox))
        {
            passwordBox.Password = (string)e.NewValue;
        }
        passwordBox.PasswordChanged += PasswordChanged;
    }
 
    private static void Attach(DependencyObject sender,
        DependencyPropertyChangedEventArgs e)
    {
        PasswordBox passwordBox = sender as PasswordBox;
 
        if (passwordBox == null)
            return;
 
        if ((bool)e.OldValue)
        {
            passwordBox.PasswordChanged -= PasswordChanged;
        }
 
        if ((bool)e.NewValue)
        {
            passwordBox.PasswordChanged += PasswordChanged;
        }
    }
 
    private static void PasswordChanged(object sender, RoutedEventArgs e)
    {
        PasswordBox passwordBox = sender as PasswordBox;
        SetIsUpdating(passwordBox, true);
        SetPassword(passwordBox, passwordBox.Password);
        SetIsUpdating(passwordBox, false);
    }
}
 
 

The Idea for this password helper was originally posted here:

http://blog.functionalfun.net/2008/06/wpf-passwordbox-and-data-binding.html



Last modified: 2014-06-22 08:58:38
Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments
Taylor Leese
Commented on 25.July 2010
I created a similar bindable password box here (http://gist.github.com/468331) as well.
Sarah
Commented on 13.August 2010
Why is the Attach method private? It causes XAML to say "The attachable property 'Attach' was not found in type 'PasswordHelper'. Not very useful.
ravi
Commented on 19.August 2010
thi is very nice
wert
Commented on 25.August 2010
twerwetr
JKOne
Commented on 28.October 2010
The Input Panel in Windows 7 doesn't work with the PasswordBox within WPF projects. Does anyone have an idea how to handle the problem?
Normand Bedard
Commented on 21.December 2010
When using validation input on passwordbox (implementing IDataErrorInfo), the red line around the box appear, but the error message text when moving mouse over the passwordbox does not appear. Any idea?
Beth
Commented on 8.February 2011
is it possible to register event then raise it from OnPasswordPropertyChanged so that the code that attaches this helper class can do post processing?
Christo...
Commented on 15.February 2011
You're essentially making the password field a dependency property. Doesn't this just circumvent the original security related issues which was the intent of not having the password field a dependency property? Aren't you just making a very big security hole by doing this?
flyinghippie
Commented on 18.February 2011
right i am on on the 20th april if you want my pass i will tell you on there the price is 50 pounds :)
flying hippie
Commented on 18.February 2011
we will bid starting on 50 and on sever polor bear
flyinghippie
Commented on 18.February 2011
on cp tell ur kids
ameen sheriff
Commented on 24.February 2011
nice.. concentrate
Siavash...
Commented on 16.March 2011
Thanks, you saved my day ;)
Daniel
Commented on 16.March 2011
Great, thank you...
Divya
Commented on 23.March 2011
Good
Jared Barneck
Commented on 9.April 2011
I am using this code, but I ran into a problem. I am also using Pages and NavigationService. Turns out the NavigationService blanks this password.

So I have a call to the navigation service, and I have to save the password, and replace it afterwards. Thought I would let you know.

Here are the details:
WPF NavigationService blanks PasswordBox.Password, which breaks the MVVM PasswordHelper
http://www.rhyous.com/2011/04/08/wpf-navigationservice-blanks-passwordbox-password-which-breaks-the-mvvm-passwordhelper/

ALI
Commented on 24.April 2011
Thanks,Can you help me about text block formatting?
I want to use approximation in text block contents,for example I have a double number like 14.34563466456 and I want to show this number in 2 float, means 14.34; how can I do it? send answer to my mail please.Thanks alot and Good Luck!

email: ALI_KHALAJI64@YAHOO.COM
karle
Commented on 29.June 2011
For my understanding this code can never run, because calling SetPassword will reset the binding. I see this in the debugger. (?!)
VINIT KUMAR
Commented on 30.June 2011
ur artical is superub Thank's for it. I want to know that cant we set a textbox's input mode to password...???
Kikoo
Commented on 21.July 2011
Great article! You made my day, thanks!!!
Praveen Gupta
Commented on 31.July 2011
good code for help me thanks
Abraham
Commented on 2.August 2011
good work ;)
Joe
Commented on 2.August 2011
Took me a while to figure this out, but here is a bit more complete bit of XAML showing how to bind. &quot;UserPass&quot; is the dependency property on the backend that I bind to:

&lt;StackPanel&gt;
&lt;PasswordBox h:PasswordHelper.Attach=&quot;True&quot; h:PasswordHelper.Password=&quot;{Binding Text, ElementName=plain, Mode=TwoWay}&quot; Width=&quot;150&quot; /&gt;
&lt;TextBlock x:Name=&quot;plain&quot; Height=&quot;0&quot; Text=&quot;{Binding UserPass, Mode=TwoWay}&quot;/&gt;
&lt;/StackPanel&gt;
Ramya
Commented on 17.September 2011
Hi I'm new to this environment could u please help me for the data binding properties of passwordbox,grid,calendar controls. Thanks in advance:)
Rakesh
Commented on 21.September 2011
that's good

Name
E-Mail (optional)
Comment