C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
As the user types, each character is replaced with a symbol—by default, a disc. We use the PasswordChanged event handler to detect changes. And we use the Password property to read the value.
Based on: .NET 4.5
Example. To begin, we drag a PasswordBox control to the window. It is placed within the Grid. And we specify the PasswordChanged event handler. In PasswordBox_PasswordChanged, we detect all modifications made to the input.
And: We then access the Password property on the PasswordBox. This returns a string, one that contains the original characters typed.
Example markup: XAML <Window x:Class="WpfApplication23.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <PasswordBox HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="100" PasswordChanged="PasswordBox_PasswordChanged"/> </Grid> </Window> Example code: C# using System.Windows; using System.Windows.Controls; namespace WpfApplication23 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e) { // ... Display Password in Title. // A bad design decision. var box = sender as PasswordBox; this.Title = "Password typed: " + box.Password; } } }
PasswordChar. Another property available is PasswordChar. When unspecified, this is left as the default value, a filled-in circle (bullet). You can use any character. But some characters will just be confusing.
So: I suggest leaving the PasswordChar as the default. The disc is a standard on web sites and program interfaces.
Discussion. How can you access the Password from a PasswordBox when the user clicks a Button? One way to do this is to assign a member field in the Window class to the value of the Password property in PasswordChanged.
And: This would avoid the need to access the PasswordBox when the Button is clicked.
So: Password validation could thus be done without even touching the PasswordBox when the button is clicked.
Summary. PasswordBox is not needed in many WPF programs. But in places where required, it helps avoid program development steps. It is simple. We access the Password property and use the PasswordChanged event handler.