How can I make a TextBox be a "password box" and display stars when using MVVM?
Solution 1:
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.
Solution 2:
As Tasnim Fabiha mentioned, it is possible to change font for TextBox in order to show only dots/asterisks. But I wasn't able to find his font...so I give you my working example:
<TextBox Text="{Binding Password}"
FontFamily="pack://application:,,,/Resources/#password" />
Just copy-paste won't work. Firstly you have to download mentioned font "password.ttf" link: https://github.com/davidagraf/passwd/blob/master/public/ttf/password.ttf Then copy that to your project Resources folder (Project->Properties->Resources->Add resource->Add existing file). Then set it's Build Action to: Resource.
After this you will see just dots, but you can still copy text from that, so it is needed to disable CTRL+C shortcut like this:
<TextBox Text="{Binding Password}"
FontFamily="pack://application:,,,/Resources/#password" >
<TextBox.InputBindings>
<!--Disable CTRL+C (COPY) -->
<KeyBinding Command="ApplicationCommands.NotACommand"
Key="C"
Modifiers="Control" />
<!--Disable CTRL+X (CUT) -->
<KeyBinding Command="ApplicationCommands.NotACommand"
Key="X"
Modifiers="Control" />
</TextBox.InputBindings>
<TextBox.ContextMenu>
<!--Hide context menu where you could copy/cut as well -->
<ContextMenu Visibility="Collapsed" />
</TextBox.ContextMenu>
</TextBox>
EDIT: Added Ctrl+X and Context menu disabling based on @CodingNinja comment, thank you.