using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; namespace BPASmart.UserManagement.Helper { /// /// 给PasswordBox添加一个可以绑定的附加类 /// public class PasswordHelper { static bool IsUpdete = false; #region PasswordProperty public static readonly DependencyProperty PasswordProperty = DependencyProperty.RegisterAttached("Password", typeof(string), typeof(PasswordHelper), new FrameworkPropertyMetadata("", new PropertyChangedCallback(OnPropertyChanged))); public static string GetPassword(DependencyObject d) { return d.GetValue(PasswordProperty).ToString(); } public static void SetPassword(DependencyObject d, string value) { d.SetValue(PasswordProperty, value); } private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { PasswordBox password = d as PasswordBox; password.PasswordChanged -= password_PasswordChanged; if (!IsUpdete) password.Password = e.NewValue?.ToString(); password.PasswordChanged += password_PasswordChanged; } #endregion #region AttachProperty public static readonly DependencyProperty AttachProperty = DependencyProperty.RegisterAttached("Attach", typeof(bool), typeof(PasswordHelper), new FrameworkPropertyMetadata(default(bool), new PropertyChangedCallback(OnAttachChanged))); public static bool GetAttach(DependencyObject d) { return (bool)d.GetValue(AttachProperty); } public static void SetAttach(DependencyObject d, bool value) { d.SetValue(AttachProperty, value); } private static void OnAttachChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { PasswordBox password = d as PasswordBox; password.PasswordChanged += password_PasswordChanged; } private static void password_PasswordChanged(object sender, RoutedEventArgs e) { PasswordBox passwordBox = sender as PasswordBox; IsUpdete = true; SetPassword(passwordBox, passwordBox.Password); IsUpdete = false; } #endregion } }