PasswordBoxHelper.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System.Windows;
  2. using System.Windows.Controls;
  3. namespace PDF_Office.Helper
  4. {
  5. public class PasswordBoxHelper
  6. {
  7. public static readonly DependencyProperty PasswordProperty = DependencyProperty.RegisterAttached(
  8. "UserPassword", typeof(string), typeof(PasswordBoxHelper), new PropertyMetadata(string.Empty, OnPasswordPropertyChanged));
  9. private static void OnPasswordPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  10. {
  11. PasswordBox passwordBox = d as PasswordBox;
  12. passwordBox.PasswordChanged -= PasswordChanged;
  13. if (!GetIsUpdating(passwordBox))
  14. {
  15. /*从Password往控件方向更新绑定值*/
  16. passwordBox.Password = e.NewValue.ToString();
  17. }
  18. passwordBox.PasswordChanged += PasswordChanged;
  19. }
  20. public static void SetPassword(DependencyObject element, string value)
  21. {
  22. element.SetValue(PasswordProperty, value);
  23. }
  24. public static string GetPassword(DependencyObject element)
  25. {
  26. return (string)element.GetValue(PasswordProperty);
  27. }
  28. public static readonly DependencyProperty AttachProperty = DependencyProperty.RegisterAttached(
  29. "Attach", typeof(bool), typeof(PasswordBoxHelper), new PropertyMetadata(false, Attach));
  30. private static void Attach(DependencyObject d, DependencyPropertyChangedEventArgs e)
  31. {
  32. if (!(d is PasswordBox passwordBox))
  33. {
  34. return;
  35. }
  36. if ((bool)e.OldValue)
  37. {
  38. passwordBox.PasswordChanged -= PasswordChanged;
  39. }
  40. if ((bool)e.NewValue)
  41. {
  42. /*当控件的值发生变化的时候,更新Password的值*/
  43. passwordBox.PasswordChanged += PasswordChanged;
  44. }
  45. }
  46. private static void PasswordChanged(object sender, RoutedEventArgs e)
  47. {
  48. PasswordBox passwordBox = sender as PasswordBox;
  49. /*IsUpdating的作用类似一把互斥锁,因涉及到双向绑定更新*/
  50. SetIsUpdating(passwordBox, true);
  51. SetPassword(passwordBox, passwordBox.Password);
  52. SetIsUpdating(passwordBox, false);
  53. }
  54. public static void SetAttach(DependencyObject element, bool value)
  55. {
  56. element.SetValue(AttachProperty, value);
  57. }
  58. public static bool GetAttach(DependencyObject element)
  59. {
  60. return (bool)element.GetValue(AttachProperty);
  61. }
  62. public static readonly DependencyProperty IsUpdatingProperty = DependencyProperty.RegisterAttached(
  63. "IsUpdating", typeof(bool), typeof(PasswordBoxHelper), new PropertyMetadata(default(bool)));
  64. public static void SetIsUpdating(DependencyObject element, bool value)
  65. {
  66. element.SetValue(IsUpdatingProperty, value);
  67. }
  68. public static bool GetIsUpdating(DependencyObject element)
  69. {
  70. return (bool)element.GetValue(IsUpdatingProperty);
  71. }
  72. }
  73. }