Microsoft.Xaml.Behaviors.Wpf
<PasswordBox>
<i:Interaction.Behaviors>
<local:PasswordBoxBindingBehavior Password="{Binding MyPassword, Mode=TwoWay}" />
</i:Interaction.Behaviors>
</PasswordBox>
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
public class PasswordBoxBindingBehavior : Behavior<PasswordBox>
{
public static readonly DependencyProperty PasswordProperty =
DependencyProperty.Register(nameof(Password), typeof(string), typeof(PasswordBoxBindingBehavior),
new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnPasswordChanged));
public string Password
{
get => (string)GetValue(PasswordProperty);
set => SetValue(PasswordProperty, value);
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.PasswordChanged += OnPasswordBoxPasswordChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.PasswordChanged -= OnPasswordBoxPasswordChanged;
}
private void OnPasswordBoxPasswordChanged(object sender, RoutedEventArgs e)
{
Password = AssociatedObject.Password;
}
private static void OnPasswordChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var behavior = (PasswordBoxBindingBehavior)d;
var passwordBox = behavior.AssociatedObject;
if (passwordBox != null && passwordBox.Password != (string)e.NewValue)
{
passwordBox.Password = (string)e.NewValue ?? string.Empty;
}
}
}