Bindable passwordBox in WPF

WPF

In WPF the Password property of the passwordBox element is not a dependency property, so we cannot bind it to anything.

The alternative, is wrapping it with a custom user control:


<UserControl x:Class="Signer1PublicInstituteClient.Components.BindablePasswordBox"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="30" d:DesignWidth="200">
    <PasswordBox x:Name="passwordBox" PasswordChanged="PasswordBox_PasswordChanged" />
</UserControl>

...

public partial class BindablePasswordBox : UserControl
{
    private bool _isPasswordChanging = false;

    public string Password
    {
        get { return (string)GetValue(PasswordProperty); }
        set { SetValue(PasswordProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Password.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty PasswordProperty =
        DependencyProperty.Register("Password", typeof(string), typeof(BindablePasswordBox), 
            new FrameworkPropertyMetadata(string.Empty, 
                FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
                PasswordPropertyChanged,
                null,
                false,
                UpdateSourceTrigger.PropertyChanged));

    private static void PasswordPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is BindablePasswordBox pBox)
        {
            pBox.UpdatePassword();
        }
    }

    private void UpdatePassword()
    {
        if (!_isPasswordChanging)
        {
            passwordBox.Password = Password;
        }
        
    }

    public BindablePasswordBox()
    {
        InitializeComponent();
    }

    private void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
    {
        _isPasswordChanging = true;
        Password = passwordBox.Password;
        _isPasswordChanging = false;
    }
}

Post a Comment

Previous Post Next Post