fastread homefastrread library fastread menu

WPF : The PasswordBox control

Tutorial by:Manisha Dubey      Date: 2016-07-11 02:42:50

❰ Previous Next ❱

For editing regular text in WPF we have the TextBox, but what about editing passwords? The functionality is very much the same, but we want WPF to display something else than the actual characters when typing in a password, to shield it from nosy people looking over your shoulder. For this purpose, WPF has the PasswordBox control, which is just as easy to use as the TextBox. Allow me to illustrate with an example:

<Window x:Class="WpfTutorialSamples.Basic_controls.PasswordBoxSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="PasswordBoxSample" Height="160" Width="300">
    <StackPanel Margin="10">
        <Label>Text:</Label>
        <TextBox />
        <Label>Password:</Label>
        <PasswordBox />
    </StackPanel>
</Window>

A simple PasswordBox control

In the screenshot, I have entered the exact same text into the two text boxes, but in the password version, the characters are replaced with dots. You can actually control which character is used instead of the real characters, using the PasswordChar property:

<PasswordBox PasswordChar="X" />

In this case, the character X will be used instead of the dots. In case you need to control the length of the password, there's a MaxLength property for you:

<PasswordBox MaxLength="6" />

I have used both properties in this updated example:

<Window x:Class="WpfTutorialSamples.Basic_controls.PasswordBoxSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="PasswordBoxSample" Height="160" Width="300">
    <StackPanel Margin="10">
        <Label>Text:</Label>
        <TextBox />
        <Label>Password:</Label>
        <PasswordBox MaxLength="6" PasswordChar="X" />
    </StackPanel>
</Window>

A simple PasswordBox control, with a couple of extra properties set

Notice how the characters are now X's instead, and that I was only allowed to enter 6 characters in the box.

PasswordBox and binding

When you need to obtain the password from the PasswordBox, you can use the Password property from Code-behind. However, for security reasons, the Password property is not implemented as a dependency property, which means that you can't bind to it.

This may or may not be important to you - as already stated, you can still read the password from Code-behind, but for MVVM implementations or if you just love data bindings, a workaround has been developed. You can read much more about it here: http://blog.functionalfun.net/2008/06/wpf-passwordbox-and-data-binding.html

❰ Previous Next ❱


WPF

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website