PasswordBox SecureString

Oct 14, 2010 at 7:31 PM

Is there any easy way to use a PasswordBox and setup a SecureString property in your ViewModel to bind to the PasswordBox.SecurePassword property?



Oct 15, 2010 at 12:29 AM

I forgot to specify, I'm talking about doing this in WPF.

Oct 15, 2010 at 1:27 PM
Edited Oct 15, 2010 at 2:02 PM

The Password property is not bindable since it is not a dependency property. This behaviour comes by design, since using DPs to store passwords is intrinsecally not safe (so should be avoided by design).

You can find more information here.

Oct 15, 2010 at 1:46 PM

Ok, that makes sense, thanks!


So what is the best way to retrieve the password from a WPF PasswordBox in the ViewModel?  Sorry if this is a noob question, I'm still trying to wrap my head around WPF/MVVM.

Oct 15, 2010 at 2:03 PM

My first answer was indeed too short and I feel that it does not answer your question fully!

You are searching for a method to bind to the SecurePassword property, but unfortunally such property is not a DependencyProperty and cannot be data-bound.

This leads to few options:

1. Write a Control that acts like a PasswordBox with a DependencyProperty to store the string (not a good idea, since it requires time to replicate all the functionalities of the original control, and lacks security, unless you define the DependencyProperty as a SecureString itself)

2. Create a control that hosts a PasswordBox, exposes a DependencyProperty for the passwords and internally handles the interaction with the Password property itself, or write an attached behaviour that serves the purpose (totally defeats the security of the PasswordBox, but is the simplest method if security is not a concern... but, honestly, it should be...)

3. Create an interface to be implemented in the View, which is consumed by the ViewModel (so the ViewModel should be aware of the View), so that you can explicitly manage the properties of the View, avoiding data-binding (this way you tighten the relationship between the View and the ViewModel, but you can benefit of all the advantages of the PasswordBox)

Note that the post I was referring to earlier, links to a sample for the second option, while the last post explicitly cites the ViewModel->View interaction to solve the problem.

Oct 20, 2010 at 7:16 PM

Thanks for the response! That was definitely helpful.