Hi people stackoverflow. I'm working with MVVM, I have ViewModel call UserViewModel with a Property Password. In the View have a control PasswordBox.
<PasswordBox x:Name="txtPassword" Password="{Binding Password}" />
But this xaml don't work. How do you do the binding?? Help please!!
For security reasons the Password property is not a dependency property and therefore you can't bind to it. Unfortunately you'll need to perform the binding in the code behind the old fashioned way (register for OnPropertyChanged event and update the value through code...)
I quick search brings me to this blog post which shows how to write an attached property to sidestep the issue. Whether this is worth doing or not though really depends on your aversion to code-behind.
You can always write a control that wraps the Password and adds a dependency property for the Password property.
I would just use code behind, but if you must you can do something like:
public class BindablePasswordBox : Decorator
{
public static readonly DependencyProperty PasswordProperty =
DependencyProperty.Register("Password", typeof(string), typeof(BindablePasswordBox));
public string Password
{
get { return (string)GetValue(PasswordProperty); }
set { SetValue(PasswordProperty, value); }
}
public BindablePasswordBox()
{
Child = new PasswordBox();
((PasswordBox)Child).PasswordChanged += BindablePasswordBox_PasswordChanged;
}
void BindablePasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
{
Password = ((PasswordBox)Child).Password;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With