PasswordHelper.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System.Windows;
  2. using System.Windows.Controls;
  3. namespace PasswordBoxPlus.Helper
  4. {
  5. public class PasswordHelper
  6. {
  7. public static readonly DependencyProperty PasswordProperty = DependencyProperty.RegisterAttached("Password", typeof(string), typeof(PasswordHelper),
  8. new PropertyMetadata(new PropertyChangedCallback(OnPropertyChanged)));
  9. public static string GetPassword(DependencyObject d)
  10. {
  11. return (string)d.GetValue(PasswordProperty);
  12. }
  13. public static void SetPassword(DependencyObject d, string value)
  14. {
  15. d.SetValue(PasswordProperty, value);
  16. }
  17. public static readonly DependencyProperty AttachProperty = DependencyProperty.RegisterAttached("Attach", typeof(string), typeof(PasswordHelper),
  18. new PropertyMetadata(new PropertyChangedCallback(OnAttachChanged)));
  19. public static string GetAttach(DependencyObject d)
  20. {
  21. return (string)d.GetValue(AttachProperty);
  22. }
  23. public static void SetAttach(DependencyObject d, string value)
  24. {
  25. d.SetValue(AttachProperty, value);
  26. }
  27. static bool isUpdating = false;
  28. private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  29. {
  30. PasswordBox passwordBox = d as PasswordBox;
  31. passwordBox.PasswordChanged -= passwordBox_PasswordChanged;
  32. if (!isUpdating)
  33. (d as PasswordBox).Password = e.NewValue.ToString();
  34. passwordBox.PasswordChanged += passwordBox_PasswordChanged;
  35. }
  36. private static void OnAttachChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  37. {
  38. PasswordBox passwordBox = d as PasswordBox;
  39. passwordBox.PasswordChanged += passwordBox_PasswordChanged;
  40. }
  41. private static void passwordBox_PasswordChanged(object sender, RoutedEventArgs e)
  42. {
  43. PasswordBox passwordBox = sender as PasswordBox;
  44. isUpdating = true;
  45. SetPassword(passwordBox, passwordBox.Password);
  46. isUpdating = false;
  47. }
  48. }
  49. }