
namespace HistoryView.Helper;

public class PassWordExtensions
{
    public static string GetPassWord(DependencyObject obj)
    {
        return (string)obj.GetValue(PassWordProperty);
    }

    public static void SetPassWord(DependencyObject obj, string value)
    {
        obj.SetValue(PassWordProperty, value);
    }

    public static readonly DependencyProperty PassWordProperty =
        DependencyProperty.RegisterAttached("PassWord", typeof(string), typeof(PassWordExtensions), new PropertyMetadata(string.Empty, OnPassWordPropertyChanged));

    static void OnPassWordPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        if (sender is not PasswordBox passWord)
            return;

        passWord.Password = (string)e.NewValue;
        MethodInfo? method = passWord.GetType().GetMethod("Select", BindingFlags.Instance | BindingFlags.NonPublic);
        method?.Invoke(passWord, [passWord.Password.Length, 0]);
    }

}
public class PasswordBehavior : Behavior<PasswordBox>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.PasswordChanged += AssociatedObject_PasswordChanged;
    }
    /// <summary>
    /// 读内容与更新内容
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void AssociatedObject_PasswordChanged(object sender, RoutedEventArgs e)
    {
        if (sender is not PasswordBox passWord)
            return;

        if (passWord.Password == PassWordExtensions.GetPassWord(passWord))
            return;

        PassWordExtensions.SetPassWord(passWord, passWord.Password);
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.PasswordChanged -= AssociatedObject_PasswordChanged;
    }
}

