Hi people stackoverflow. I\'m working with MVVM, I have ViewModel call UserViewModel with a Property Password. In the View have a control P
There is an issue with the BindablePasswordBox. It only works in one direction, PasswordBox to PasswordProperty. Below is a modified version of it that works in both directions. It registers a PropertyChangedCallback and updates the PasswordBox's Password when it is called. I hope that someone finds this useful.
public class BindablePasswordBox : Decorator
{
public static readonly DependencyProperty PasswordProperty = DependencyProperty.Register("Password", typeof(string), typeof(BindablePasswordBox), new PropertyMetadata(string.Empty, OnDependencyPropertyChanged));
public string Password
{
get { return (string)GetValue(PasswordProperty); }
set { SetValue(PasswordProperty, value); }
}
private static void OnDependencyPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
BindablePasswordBox p = source as BindablePasswordBox;
if (p != null)
{
if (e.Property == PasswordProperty)
{
var pb = p.Child as PasswordBox;
if (pb != null)
{
if (pb.Password != p.Password)
pb.Password = p.Password;
}
}
}
}
public BindablePasswordBox()
{
Child = new PasswordBox();
((PasswordBox)Child).PasswordChanged += BindablePasswordBox_PasswordChanged;
}
void BindablePasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
{
Password = ((PasswordBox)Child).Password;
}
}