C# / WPF Unmask password inside the passwordBox

Benjamin Guino picture Benjamin Guino · Jun 25, 2015 · Viewed 18.4k times · Source

How could I unmasked and masked the password inside the passwordBox whenever I click the checkBox? I'm using C# WPF template.

Here is my .XAML code:

<PasswordBox x:Name="passwordBox_password" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" Margin="5" Height="25" />
        <CheckBox x:Name="checkBox_showPassword" Grid.Row="3" Grid.Column="1" Margin="5,0,5,5" Content="show password" Checked="checkBox_showPassword_Checked" Unchecked="checkBox_showPassword_Unchecked" />

Here is my .CS code:

private void checkBox_showPassword_Checked(object sender, RoutedEventArgs e)
    {
        // what to do here ?
    }

    private void checkBox_showPassword_Unchecked(object sender, RoutedEventArgs e)
    {
        // what to do here ?
    }

Or is there another way to do it in WPF?

Answer

Marco Concas picture Marco Concas · May 14, 2019

It's very simple to do that. First you should to add the value PasswordChar in your PasswordBox:

<PasswordBox Name="PasswordHidden" PasswordChar="•"/>

Next under the PasswordBox tag you should to add a TextBox with Visibility value setted to Hidden:

<TextBox Name="PasswordUnmask" Visibility="Hidden"/>

And a trigger to show / hide the password, for example a simple text or a button. In my case I'm using a simple text.

<TextBlock Name="ShowPassword"/>

Next you need to add 3 different events in the trigger element, for example (this is valid for TextBlock or Image, if you want to use a Button you should to choose another events):

<TextBlock x:Name="ShowPassword" Text="SHOW" PreviewMouseDown="ShowPassword_PreviewMouseDown" PreviewMouseUp="ShowPassword_PreviewMouseUp" MouseLeave="ShowPassword_MouseLeave"/>

The events are PreviewMouseDown PreviewMouseUp and MouseLeave but you can choose the appropriate event for your situation.

Now in your code you need to program the functions:

private void ShowPassword_PreviewMouseDown(object sender, MouseButtonEventArgs e) => ShowPasswordFunction();
private void ShowPassword_PreviewMouseUp(object sender, MouseButtonEventArgs e) => HidePasswordFunction();
private void ShowPassword_MouseLeave(object sender, MouseEventArgs e) => HidePasswordFunction();

private void ShowPasswordFunction()
{
    ShowPassword.Text = "HIDE";
    PasswordUnmask.Visibility = Visibility.Visible;
    PasswordHidden.Visibility = Visibility.Hidden;
    PasswordUnmask.Text = PasswordHidden.Password;
}

private void HidePasswordFunction()
{
    ShowPassword.Text = "SHOW";
    PasswordUnmask.Visibility = Visibility.Hidden;
    PasswordHidden.Visibility = Visibility.Visible;
}