PasswordBoxHelper.cs 3.0 KB

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