views:

1357

answers:

2

How can I do this in XAML:

PSEUDO-CODE:

<TextBox Text="{Binding Password}" Type="Password"/>

so that the user sees stars or dots when he is typing in the password.

I've tried various examples which suggest PasswordChar and PasswordBox but can't get these to work.

e.g. I can do this as shown here:

<PasswordBox Grid.Column="1" Grid.Row="1"
    PasswordChar="*"/>

but I of course want to bind the Text property to my ViewModel so I can send the value the bound TextBox when the button is clicked (not working with code behind), I want to do this:

<TextBox Grid.Column="1" Grid.Row="0" 
    Text="{Binding Login}" 
    Style="{StaticResource FormTextBox}"/>
<PasswordBox Grid.Column="1" Grid.Row="1"
    Text="{Binding Password}" 
    PasswordChar="*"
    Style="{StaticResource FormTextBox}"/>

But PasswordBox doesn't have a Text property.

+2  A: 

To get or set the Password in a PasswordBox, use the Password property. Such as

string password = PasswordBox.Password;

This doesn't support Databinding as far as I know, so you'd have to set the value in the codebehind, and update it accordingly.

Brandon
Could mention: <PasswordBox ... Password="{Binding Password}" ... />
sixlettervariables
I don't think that actually works, at least not when I tried.
Brandon
if I define the value of my password box in code-behind, then it is no longer unit testable, surely I can bind the password from the viewmodel somehow
Edward Tanguay
As was mentioned in the question you found earlier (the accepted answer), there is a way to work around this issue, its just a matter of whether you think its worth the extra code. The code behind is the simplest way to do it.
Brandon
the article rightly states "it's a shame not to be able to use data binding" but it does offers a 2-page attached-property workaround, let's see if it actually works: http://blog.functionalfun.net/2008/06/wpf-passwordbox-and-data-binding.html
Edward Tanguay
the reason for not allowing databinding on PasswordBox seems to be a security concern discussed here: http://social.msdn.microsoft.com/forums/en-US/wpf/thread/7ca97b60-2d8e-4a27-8c5b-b8d5d7370a5e/
Edward Tanguay
Ah, makes sense. Hopefully they manage to secure the databinding in the next release. Thanks for the link.
Brandon
I tested this solution and it works very nicely: http://blog.functionalfun.net/2008/06/wpf-passwordbox-and-data-binding.html
Edward Tanguay
+1  A: 

There's a way to bind on a PasswordBox here: PasswordBox Databinding