Home
WPF
PasswordBox Control
This page was last reviewed on Sep 29, 2022.
Dot Net Perls
PasswordBox. As the user types, each character in a PasswordBox replaced with a symbol—by default, a disc. We use the PasswordChanged event handler to detect changes.
Control notes. We use the Password property to read the value from the PasswordBox. To begin, please drag a PasswordBox control to your WPF window.
Example. Here 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.
<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>
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.
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? We can assign a member field in the Window class to the value of the Password property in PasswordChanged.
Tip 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. But in places where passwords are required, PasswordBox helps avoid program development steps. We can access the Password property and use the PasswordChanged event handler.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 29, 2022 (edit).
Home
Changes
© 2007-2024 Sam Allen.