showing password characters on some event for passwordbox

22,964

Solution 1

Don't think that is possible with PasswordBox... just a thought, but you might accomplish the same result using a hidden TextBox and when the user clicks the CheckBox, you just hide the PasswordBox and show the TextBox; if he clicks again, you switch their Visibility state again, and so on...

Edit

And here it is how!

Just add a page, change the ContentPanel to a StackPanel and add this XAML code:

<PasswordBox x:Name="MyPasswordBox" Password="{Binding Text, Mode=TwoWay, ElementName=MyTextBox}"/>
<TextBox x:Name="MyTextBox" Text="{Binding Password, Mode=TwoWay, ElementName=MyPasswordBox}" Visibility="Collapsed" />
<CheckBox x:Name="ShowPasswordCharsCheckBox" Content="Show password" Checked="ShowPasswordCharsCheckBox_Checked" Unchecked="ShowPasswordCharsCheckBox_Unchecked" />

Next, on the page code, add the following:

private void ShowPasswordCharsCheckBox_Checked(object sender, RoutedEventArgs e)
{
    MyPasswordBox.Visibility = System.Windows.Visibility.Collapsed;
    MyTextBox.Visibility = System.Windows.Visibility.Visible;

    MyTextBox.Focus();
}

private void ShowPasswordCharsCheckBox_Unchecked(object sender, RoutedEventArgs e)
{
    MyPasswordBox.Visibility = System.Windows.Visibility.Visible;
    MyTextBox.Visibility = System.Windows.Visibility.Collapsed;

    MyPasswordBox.Focus();
}

This works fine, but with a few more work, you can do this fully MVVM'ed!

Solution 2

I created an MVVM example, which I'm also using in real life. Please note that PasswordBox.Password is not a Dependency Property and thus cannot be bound directly. It's designed like that for security reasons, for details see: How to bind to a PasswordBox in MVVM

If you want to do it anyway, you have to build a bridge to your view model using code behind. I'm not providing the converters, as you're probably using your own set of converters. If not, please ask google for suitable implementations.

EnterPasswordWindow.xaml

<Window x:Class="MyDemoApp.Controls.EnterPasswordWindow"
        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:MyDemoApp.Controls"
        mc:Ignorable="d" d:DataContext="{d:DesignInstance local:EnterPasswordViewModel}"
        WindowStartupLocation="CenterOwner" ResizeMode="NoResize" SizeToContent="WidthAndHeight"
        Title="Enter Password">
    <StackPanel Margin="4">
        <TextBlock Margin="4">Please enter a password:</TextBlock>
        <TextBox Margin="4" Text="{Binding Password, UpdateSourceTrigger=PropertyChanged}" Visibility="{Binding ShowPassword, Converter={StaticResource BoolToVisibleConverter}}"/>
        <PasswordBox Margin="4" Name="PasswordBox" Visibility="{Binding ShowPassword, Converter={StaticResource BoolToCollapsedConverter}}" PasswordChanged="PasswordBox_PasswordChanged"/>
        <CheckBox Margin="4" IsChecked="{Binding ShowPassword}">Show password</CheckBox>
        <DockPanel>
            <Button Margin="4" Width="150" Height="30" IsDefault="True" IsEnabled="{Binding Password, Converter={StaticResource StringIsNotNullOrEmptyConverter}}" Click="Button_Click">OK</Button>
            <Button Margin="4" Width="150" Height="30" IsCancel="True" HorizontalAlignment="Right">Cancel</Button>
        </DockPanel>
    </StackPanel>
</Window>

EnterPasswordWindow.xaml.cs

using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace MyDemoApp.Controls
{
    /// <summary>
    /// Interaction logic for EnterPasswordWindow.xaml
    /// </summary>
    public partial class EnterPasswordWindow : Window
    {
        public EnterPasswordWindow()
        {
            InitializeComponent();
            DataContext = ViewModel = new EnterPasswordViewModel();
            ViewModel.PropertyChanged += ViewModel_PropertyChanged;
        }

        public EnterPasswordViewModel ViewModel { get; set; }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = true;
            Close();
        }

        private void ViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (!mSuppressPropertyChangedEvent && e.PropertyName == nameof(ViewModel.Password))
            {
                PasswordBox.Password = ViewModel.Password;
            }
        }
        private bool mSuppressPropertyChangedEvent;
        private void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
        {
            mSuppressPropertyChangedEvent = true;
            ViewModel.Password = ((PasswordBox)sender).Password;
            mSuppressPropertyChangedEvent = false;
        }
    }
}

EnterPasswordViewModel.cs

using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace MyDemoApp.Controls
{
    public class EnterPasswordViewModel : INotifyPropertyChanged
    {
        public string Password
        {
            get => mPassword;
            set
            {
                if (mPassword != value)
                {
                    mPassword = value;
                    NotifyPropertyChanged();
                }
            }
        }
        private string mPassword;

        public bool ShowPassword
        {
            get => mShowPassword;
            set
            {
                if (mShowPassword != value)
                {
                    mShowPassword = value;
                    NotifyPropertyChanged();
                }
            }
        }
        private bool mShowPassword;

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged([CallerMemberName]string propertyName = null)
        {
            if (string.IsNullOrEmpty(propertyName))
            {
                return;
            }
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Solution 3

with default passwordbox it's not possible to implement the feature you want.

more information you can find here: http://social.msdn.microsoft.com/Forums/en/wpf/thread/98d0d4d4-1463-481f-b8b1-711119a6ba99

Share:
22,964
rakesh
Author by

rakesh

Learning,improving

Updated on July 09, 2022

Comments

  • rakesh
    rakesh almost 2 years

    I am developing a windows phone application.In that i ask the user to login.

    On the login page the user has to enter password.

    Now what I want is that i give user a check box which when selected should show the characters of the password.

    I have not seen any property on password box to show password characters.

    Please suggest some way to do it.

  • Pedro Lamas
    Pedro Lamas about 12 years
    That post is quite old and right now does not reflect the true nature of PasswordBox.Password, because right now this is a Dependency Property so you can bind to it!
  • tux007
    tux007 over 7 years
    Well, it doesn't work, because VS2015 says, you can't bind the password of a passwordbox :(
  • Romain Hautefeuille
    Romain Hautefeuille almost 6 years
    yep, not working anymore, maybe update your answer in that way.
  • Kim Homann
    Kim Homann almost 4 years
    And for full MVVM'iness, you should also use Visibility="{Binding ShowPassword, Converter={StaticResource BoolToHiddenConverter}}" or similar. Don't set the Visibility in code behind.