想要扩展该控件时发现PasswordBox是一个密封类,是不可继承的。
故通过附加属性来实现该功能。
声明了两个附加属性
IsPasswordBindingEnabled:用来指示密码是否可用来绑定,当值发生改变时订阅或者取消订阅当Password改变时同步用于绑定的密码附加属性
BindedPassword:用于绑定的密码,与密码同步,当值发生改变是时与Password同步
/// <summary> /// 扩展密码框密码可用于绑定的帮助类 /// </summary> public class BindedPasswordHelper { #region 指示密码框的密码是否可以绑定的附加属性 public static bool GetIsPasswordBindingEnabled(DependencyObject obj) { return (bool)obj.GetValue(IsPasswordBindingEnabledProperty); } public static void SetIsPasswordBindingEnabled(DependencyObject obj, bool value) { obj.SetValue(IsPasswordBindingEnabledProperty, value); } public static readonly DependencyProperty IsPasswordBindingEnabledProperty = DependencyProperty.RegisterAttached("IsPasswordBindingEnabled", typeof(bool), typeof(BindedPasswordHelper), new UIPropertyMetadata(false, OnIsPasswordBindingEnabledChanged)); private static void OnIsPasswordBindingEnabledChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) { var passwordBox = obj as PasswordBox; if (passwordBox != null) { passwordBox.PasswordChanged -= PasswordBoxPasswordChanged; if ((bool)e.NewValue) { passwordBox.PasswordChanged += PasswordBoxPasswordChanged; } } } //当密码发生改变时,更新用于绑定的密码 private static void PasswordBoxPasswordChanged(object sender, RoutedEventArgs e) { var passwordBox = (PasswordBox)sender; if (!string.Equals(GetBindedPassword(passwordBox), passwordBox.Password)) { SetBindedPassword(passwordBox, passwordBox.Password); } } #endregion #region 用于绑定的密码的附加属性 public static string GetBindedPassword(DependencyObject obj) { return (string)obj.GetValue(BindedPasswordProperty); } public static void SetBindedPassword(DependencyObject obj, string value) { obj.SetValue(BindedPasswordProperty, value); } public static readonly DependencyProperty BindedPasswordProperty = DependencyProperty.RegisterAttached("BindedPassword", typeof(string), typeof(BindedPasswordHelper), new UIPropertyMetadata(string.Empty, OnBindedPasswordChanged)); //当被绑定的密码更新时,更新密码 private static void OnBindedPasswordChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) { var passwordBox = obj as PasswordBox; if (passwordBox != null && e.NewValue != null && passwordBox.Password != e.NewValue.ToString()) { passwordBox.Password = e.NewValue.ToString(); } } #endregion }
使用方法,这里要特别注意,与TextBox类似,一定要声明Mode已经UpdateSourceTrigger,不然绑定的值不会与后台的属性同步
<PasswordBox Style="{StaticResource PasswordBoxStyle}" helper:BindedPasswordHelper.IsPasswordBindingEnabled="True" helper:BindedPasswordHelper.BindedPassword="{Binding Password,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>