TOC

The community is working on translating this tutorial into Bulgarian, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Основни контрол-и:

The PasswordBox control

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>

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>

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


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!