The PasswordBox is similar to the TextBox except that we don’t want to display the characters that the user is typing in. You can use the PasswordChar property to change the displayed character from a circle to something else, that you enclose in double-quotes. If you need to control the length of the characters there is the MaxLength property.
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. The Password property is a plain CLR property rather than a Dependency Property, so it doesn’t support being the target of a Data binding. So internally the PasswordBox stores the password in a good old field, and in fact holds it using a SecureString – a string that is automatically encrypted in memory and obliterated when no longer needed. However, you can still read the password from Code-behind, or use this work-around.
<Window x:Class="PasswordBoxSimple.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:PasswordBoxSimple" mc:Ignorable="d" WindowStartupLocation="CenterScreen" Title="PasswordBoxSimple" Height="150" Width="300"> <StackPanel Margin="10"> <Label>Text:</Label> <TextBox /> <Label>Password:</Label> <PasswordBox /> </StackPanel> </Window>
We’ve done nothing to the code behind.
using System.Windows; namespace PasswordBoxSimple { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } } }