PasswordHelper.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System.Windows;
  2. using System.Windows.Controls;
  3. namespace SHJX.Service.Common.ExtendElement
  4. {
  5. public static class PasswordHelper
  6. {
  7. public static readonly DependencyProperty PasswordProperty =
  8. DependencyProperty.RegisterAttached("Password",
  9. typeof(string), typeof(PasswordHelper),
  10. new FrameworkPropertyMetadata(string.Empty, OnPasswordPropertyChanged));
  11. public static readonly DependencyProperty AttachProperty =
  12. DependencyProperty.RegisterAttached("Attach",
  13. typeof(bool), typeof(PasswordHelper), new PropertyMetadata(false, Attach));
  14. private static readonly DependencyProperty IsUpdatingProperty =
  15. DependencyProperty.RegisterAttached("IsUpdating", typeof(bool),
  16. typeof(PasswordHelper));
  17. public static void SetAttach(DependencyObject dp, bool value)
  18. {
  19. dp.SetValue(AttachProperty, value);
  20. }
  21. public static bool GetAttach(DependencyObject dp)
  22. {
  23. return (bool)dp.GetValue(AttachProperty);
  24. }
  25. public static string GetPassword(DependencyObject dp)
  26. {
  27. return (string)dp.GetValue(PasswordProperty);
  28. }
  29. public static void SetPassword(DependencyObject dp, string value)
  30. {
  31. dp.SetValue(PasswordProperty, value);
  32. }
  33. private static bool GetIsUpdating(DependencyObject dp)
  34. {
  35. return (bool)dp.GetValue(IsUpdatingProperty);
  36. }
  37. private static void SetIsUpdating(DependencyObject dp, bool value)
  38. {
  39. dp.SetValue(IsUpdatingProperty, value);
  40. }
  41. private static void OnPasswordPropertyChanged(DependencyObject sender,
  42. DependencyPropertyChangedEventArgs e)
  43. {
  44. if (sender is PasswordBox passwordBox)
  45. {
  46. passwordBox.PasswordChanged -= PasswordChanged;
  47. if (!GetIsUpdating(passwordBox))
  48. {
  49. passwordBox.Password = (string)e.NewValue;
  50. }
  51. passwordBox.PasswordChanged += PasswordChanged;
  52. }
  53. }
  54. private static void Attach(DependencyObject sender, DependencyPropertyChangedEventArgs e)
  55. {
  56. if (sender is not PasswordBox passwordBox)
  57. return;
  58. if ((bool)e.OldValue)
  59. {
  60. passwordBox.PasswordChanged -= PasswordChanged;
  61. }
  62. if ((bool)e.NewValue)
  63. {
  64. passwordBox.PasswordChanged += PasswordChanged;
  65. }
  66. }
  67. private static void PasswordChanged(object sender, RoutedEventArgs e)
  68. {
  69. if (sender is PasswordBox passwordBox)
  70. {
  71. SetIsUpdating(passwordBox, true);
  72. SetPassword(passwordBox, passwordBox.Password);
  73. SetIsUpdating(passwordBox, false);
  74. }
  75. }
  76. }
  77. }