We have the following scenario:
PasswordBox
)
I have solved this problem by creating a UserControl that exposes a SecureString dependency property that can be bound to. This method keeps the password in a SecureString at all times, and doesn't "break" MVVM.
XAML
CS
public partial class PasswordUserControl : UserControl
{
public SecureString Password
{
get { return (SecureString) GetValue(PasswordProperty); }
set { SetValue(PasswordProperty, value); }
}
public static readonly DependencyProperty PasswordProperty =
DependencyProperty.Register("Password", typeof(SecureString), typeof(UserCredentialsInputControl),
new PropertyMetadata(default(SecureString)));
public PasswordUserControl()
{
InitializeComponent();
// Update DependencyProperty whenever the password changes
PasswordBox.PasswordChanged += (sender, args) => {
Password = ((PasswordBox) sender).SecurePassword;
};
}
}
Using the control is very straightforward, just bind the password DependencyProperty on the control to a Password property on your ViewModel. The ViewModel's Password property should be a SecureString.
Change the Mode and UpdateSource trigger on the binding to whatever is best for you.
If you need the password in plain text, the following page describes the proper way to convert between SecureString and string: http://blogs.msdn.com/b/fpintos/archive/2009/06/12/how-to-properly-convert-securestring-to-string.aspx. Of course you shouldn't store the plain text string...