PasswordBoxHelper.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System.Windows;
  2. using System.Windows.Controls;
  3. namespace PDF_Office.Helper
  4. {
  5. public class PasswordBoxHelper
  6. {
  7. // 包含两个依赖附加属性 Password Attach
  8. public static readonly DependencyProperty PasswordProperty = DependencyProperty.RegisterAttached("Password", typeof(string), typeof(PasswordBoxHelper),
  9. new PropertyMetadata(new PropertyChangedCallback(OnPropertyChanged)));
  10. public static string GetPassword(DependencyObject d)
  11. {
  12. return (string)d.GetValue(PasswordProperty);
  13. }
  14. public static void SetPassword(DependencyObject d, string value)
  15. {
  16. d.SetValue(PasswordProperty, value);
  17. }
  18. public static readonly DependencyProperty AttachProperty = DependencyProperty.RegisterAttached("Attach", typeof(string), typeof(PasswordBoxHelper),
  19. new PropertyMetadata(new PropertyChangedCallback(OnAttachChanged)));
  20. public static string GetAttach(DependencyObject d)
  21. {
  22. return (string)d.GetValue(PasswordProperty);
  23. }
  24. public static void SetAttach(DependencyObject d, string value)
  25. {
  26. d.SetValue(PasswordProperty, value);
  27. }
  28. public static readonly DependencyProperty DisplayTextProperty = DependencyProperty.RegisterAttached("DisplayText", typeof(string), typeof(PasswordBoxHelper));
  29. public static string GetDisplayText(DependencyObject d)
  30. {
  31. return (string)d.GetValue(PasswordProperty);
  32. }
  33. public static void SetDisplayText(DependencyObject d, string value)
  34. {
  35. d.SetValue(PasswordProperty, value);
  36. }
  37. static bool _isUpdating = false;
  38. private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  39. {
  40. PasswordBox pb = (d as PasswordBox);
  41. pb.PasswordChanged -= Pb_PasswordChanged;
  42. if (!_isUpdating)
  43. (d as PasswordBox).Password = e.NewValue.ToString();
  44. pb.PasswordChanged += Pb_PasswordChanged;
  45. }
  46. private static void OnAttachChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  47. {
  48. PasswordBox pb = (d as PasswordBox);
  49. pb.PasswordChanged += Pb_PasswordChanged;
  50. }
  51. private static void Pb_PasswordChanged(object sender, RoutedEventArgs e)
  52. {
  53. PasswordBox pb = (sender as PasswordBox);
  54. _isUpdating = true;
  55. SetPassword(pb, pb.Password);
  56. _isUpdating = false;
  57. }
  58. }
  59. }