3 using System.Windows.Controls;
4 using System.Windows.Data;
6 namespace SpeedportHybridControl.Implementations
9 // http://blog.functionalfun.net/2008/06/wpf-passwordbox-and-data-binding.html
10 public static class PasswordHelper
12 public static readonly DependencyProperty BoundPassword =
13 DependencyProperty.RegisterAttached("BoundPassword", typeof(string), typeof(PasswordHelper), new PropertyMetadata(string.Empty, OnBoundPasswordChanged));
15 public static readonly DependencyProperty BindPassword = DependencyProperty.RegisterAttached(
16 "BindPassword", typeof(bool), typeof(PasswordHelper), new PropertyMetadata(false, OnBindPasswordChanged));
18 private static readonly DependencyProperty UpdatingPassword =
19 DependencyProperty.RegisterAttached("UpdatingPassword", typeof(bool), typeof(PasswordHelper), new PropertyMetadata(false));
21 private static void OnBoundPasswordChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
23 PasswordBox box = d as PasswordBox;
25 // only handle this event when the property is attached to a PasswordBox
26 // and when the BindPassword attached property has been set to true
27 if (d == null || !GetBindPassword(d))
32 // avoid recursive updating by ignoring the box's changed event
33 box.PasswordChanged -= HandlePasswordChanged;
35 string newPassword = (string)e.NewValue;
37 if (!GetUpdatingPassword(box))
39 box.Password = newPassword;
42 box.PasswordChanged += HandlePasswordChanged;
45 private static void OnBindPasswordChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
47 // when the BindPassword attached property is set on a PasswordBox,
48 // start listening to its PasswordChanged event
50 PasswordBox box = dp as PasswordBox;
57 bool wasBound = (bool)(e.OldValue);
58 bool needToBind = (bool)(e.NewValue);
62 box.PasswordChanged -= HandlePasswordChanged;
67 box.PasswordChanged += HandlePasswordChanged;
71 private static void HandlePasswordChanged(object sender, RoutedEventArgs e)
73 PasswordBox box = sender as PasswordBox;
75 // set a flag to indicate that we're updating the password
76 SetUpdatingPassword(box, true);
77 // push the new password into the BoundPassword property
78 SetBoundPassword(box, box.Password);
79 SetUpdatingPassword(box, false);
82 public static void SetBindPassword(DependencyObject dp, bool value)
84 dp.SetValue(BindPassword, value);
87 public static bool GetBindPassword(DependencyObject dp)
89 return (bool)dp.GetValue(BindPassword);
92 public static string GetBoundPassword(DependencyObject dp)
94 return (string)dp.GetValue(BoundPassword);
97 public static void SetBoundPassword(DependencyObject dp, string value)
99 dp.SetValue(BoundPassword, value);
102 private static bool GetUpdatingPassword(DependencyObject dp)
104 return (bool)dp.GetValue(UpdatingPassword);
107 private static void SetUpdatingPassword(DependencyObject dp, bool value)
109 dp.SetValue(UpdatingPassword, value);