PasswordBoxHelper.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System.Windows;
  2. using System.Windows.Controls;
  3. namespace vCloudUploaderDemo
  4. {
  5. public static class PasswordBoxHelper
  6. {
  7. public static readonly DependencyProperty PasswordProperty =
  8. DependencyProperty.RegisterAttached("Password",
  9. typeof(string), typeof(PasswordBoxHelper),
  10. new FrameworkPropertyMetadata(null, OnPasswordPropertyChanged));
  11. public static readonly DependencyProperty AttachProperty =
  12. DependencyProperty.RegisterAttached("Attach",
  13. typeof(bool), typeof(PasswordBoxHelper), new PropertyMetadata(false, Attach));
  14. private static readonly DependencyProperty IsUpdatingProperty =
  15. DependencyProperty.RegisterAttached("IsUpdating", typeof(bool),
  16. typeof(PasswordBoxHelper));
  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. var passwordBox = sender as PasswordBox;
  45. if (passwordBox != null)
  46. {
  47. passwordBox.PasswordChanged -= PasswordChanged;
  48. if (!GetIsUpdating(passwordBox))
  49. {
  50. passwordBox.Password = (string)e.NewValue;
  51. }
  52. passwordBox.PasswordChanged += PasswordChanged;
  53. }
  54. }
  55. private static void Attach(DependencyObject sender,
  56. DependencyPropertyChangedEventArgs e)
  57. {
  58. var 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. var passwordBox = sender as PasswordBox;
  73. if (passwordBox != null)
  74. {
  75. SetIsUpdating(passwordBox, true);
  76. SetPassword(passwordBox, passwordBox.Password);
  77. SetIsUpdating(passwordBox, false);
  78. }
  79. }
  80. }
  81. }