I would like to bind the User.Password property to PasswordBox (TwoWay). Since PasswordBox.Password is not binding, I did AttachedProperties to fix this (one to activate the binding and one to store the actual password). The problem is that they will not bind (GetBindingExpression returns null).
also:
- Work of AttachedProperties. Password and PasswordValue (attached) are set correctly if I enter the password in PasswordBox, but User.Password remains empty.
- AttachedProperty binding also works, but just the opposite: if I bind PasswordValue to TextBlock (TextBlock.Text is target, helper: PasswordValue is source), it works. Only I cannot use this because User properties are not dependency objects.
- User.Password is a binder (User implements INotifyPropertyChanged), and I managed to associate User.Username with TextBox.Text and (Username and password are similar string properties)
Here are the AttachedProperties:
public static bool GetTurnOnBinding(DependencyObject obj) { return (bool)obj.GetValue(TurnOnBindingProperty); } public static void SetTurnOnBinding(DependencyObject obj, bool value) { obj.SetValue(TurnOnBindingProperty, value); } // Using a DependencyProperty as the backing store for TurnOnBinding. This enables animation, styling, binding, etc... public static readonly DependencyProperty TurnOnBindingProperty = DependencyProperty.RegisterAttached( "TurnOnBinding", typeof(bool), typeof(PasswordHelper), new UIPropertyMetadata(false, (d, e) => { var pb = d as PasswordBox; SetPasswordValue(pb, pb.Password); pb.PasswordChanged += (s, x) => SetPasswordValue(pb, pb.Password); })); public static string GetPasswordValue(DependencyObject obj) { return (string)obj.GetValue(PasswordValueProperty); } public static void SetPasswordValue(DependencyObject obj, string value) { obj.SetValue(PasswordValueProperty, value); } // Using a DependencyProperty as the backing store for PasswordValue. This enables animation, styling, binding, etc... public static readonly DependencyProperty PasswordValueProperty = DependencyProperty.RegisterAttached( "PasswordValue", typeof(string), typeof(PasswordHelper), new UIPropertyMetadata(null, (d, e) => { PasswordBox p = d as PasswordBox; string s = e.NewValue as string; if (p.Password != s) p.Password = s; }));
And the part of XAML with binding:
<PasswordBox x:Name="passBox" root:PasswordHelper.TurnOnBinding="True" root:PasswordHelper.PasswordValue="{Binding Text, ElementName=passSupport, Mode=TwoWay}"/>
source share