PasswordBoxAttach.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System.Windows;
  2. using HandyControl.Data;
  3. namespace HandyControl.Controls;
  4. public class PasswordBoxAttach
  5. {
  6. /// <summary>
  7. /// 密码长度
  8. /// </summary>
  9. public static readonly DependencyProperty PasswordLengthProperty = DependencyProperty.RegisterAttached(
  10. "PasswordLength", typeof(int), typeof(PasswordBoxAttach), new PropertyMetadata(ValueBoxes.Int0Box));
  11. public static void SetPasswordLength(DependencyObject element, int value) => element.SetValue(PasswordLengthProperty, value);
  12. public static int GetPasswordLength(DependencyObject element) => (int) element.GetValue(PasswordLengthProperty);
  13. /// <summary>
  14. /// 是否监测
  15. /// </summary>
  16. public static readonly DependencyProperty IsMonitoringProperty = DependencyProperty.RegisterAttached(
  17. "IsMonitoring", typeof(bool), typeof(PasswordBoxAttach), new FrameworkPropertyMetadata(ValueBoxes.FalseBox, FrameworkPropertyMetadataOptions.Inherits, OnIsMonitoringChanged));
  18. private static void OnIsMonitoringChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  19. {
  20. if (d is System.Windows.Controls.PasswordBox passwordBox)
  21. {
  22. if (e.NewValue is bool boolValue)
  23. {
  24. if (boolValue)
  25. {
  26. passwordBox.PasswordChanged += PasswordChanged;
  27. }
  28. else
  29. {
  30. passwordBox.PasswordChanged -= PasswordChanged;
  31. }
  32. }
  33. }
  34. }
  35. public static void SetIsMonitoring(DependencyObject element, bool value) => element.SetValue(IsMonitoringProperty, ValueBoxes.BooleanBox(value));
  36. public static bool GetIsMonitoring(DependencyObject element) => (bool) element.GetValue(IsMonitoringProperty);
  37. private static void PasswordChanged(object sender, RoutedEventArgs e)
  38. {
  39. if (sender is System.Windows.Controls.PasswordBox passwordBox)
  40. {
  41. SetPasswordLength(passwordBox, passwordBox.Password.Length);
  42. }
  43. }
  44. }