Bookmark and Share Share...    Subscribe to this feed Feed   About me...


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


 Comments on this article

Show all comments
Patel Dishant
Commented on 1.July 2009
Can I Create or call the css File in SilverLight
satya
Commented on 11.August 2009
I want like vista password textbox type , I meen initialy passwordtextbox contains "password",when the user going to enter his password it will be shown only "*"s like that..
mo
Commented on 8.September 2009
@satya: google for wpf watermark
@Tan: "Namespace.to.Passwordhepler" is a placeholder. Fill in your own Namespace and learn how to post
Manoj
Commented on 15.October 2009
How to run this code as I am very new to programming
Malu
Commented on 6.November 2009
Too Simple but lack content
Senthil
Commented on 18.November 2009
How to validate the passwordbox or any textbox for required validation and also for Regular expression validation.
Senthil
Commented on 18.November 2009
How to redirect to another page on clicking button and also how to check the password is correct as in sql database.
Senthil
Commented on 18.November 2009
I had create a page in which there are two text box and a button onclicking that button I have to save the value in textbox in database.

Can any one give the code for this scenario. I m new to WPF
Rajagopal
Commented on 19.November 2009
article is great...
sudha
Commented on 2.December 2009
Good article...
amit
Commented on 11.December 2009
good article
to reset password box text use
password1.clear();
harshad
Commented on 15.December 2009
can anybody please put the namespace required for the passwordhelper?
harshad
Commented on 15.December 2009
sorry my bad.......!!! i didnt see the class below.
Chinu
Commented on 24.December 2009
Good article...
Great
Commented on 4.January 2010
It explains well about the dependency property too :)
waqas
Commented on 5.January 2010
extremly superb introductory material..... very good effort.
kd
Commented on 7.April 2010
hi..in order to use this password textbox, do we need to add any references? because when i try to put PasswordBox in my page, there were an error.
PLM
Commented on 26.May 2010
As anyone manage to have that logic working in VB.NET? I am able to have that example working in C# but getting issue with VB.NET.

I have a PasswordHelper class that compiles but when I try to add the properties to my PasswordBox it does not recognize them (evenknow I have the correct namespace at the top of my UserControl)
PLM
Commented on 26.May 2010
As anyone manage to have that logic working in VB.NET? I am able to have that example working in C# but getting issue with VB.NET.

I have a PasswordHelper class that compiles but when I try to add the properties to my PasswordBox it does not recognize them (evenknow I have the correct namespace at the top of my UserControl)
rahul bhojane
Commented on 3.June 2010
Good article...
David
Commented on 24.June 2010
Very helpfull, though I had some trouble converting the code to c# only (no XAML)

still not sure how the PasswordHelper got attached, since I was not able to translate this line in C# :

PasswordBox w:PasswordHelper.Attach="True"

but it seems the property works fine so... guess the attachment is kind of transparent in my code, for whatever reason...
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

Name
E-Mail (optional)
Comment
About Christian Moser