The task is «creating a password input field with the option to show or hide the password». There are no security requirements, so working with the password can be done in a string type.
At the moment, this can be solved quite simply by using a font with a single mask character in the TextBox. When triggered by a regular CheckBox, the font is replaced with a masking font or vice versa. But such a masking font must be prepared in advance.
But recently they gave an additional condition “the ability to change the masking symbol.” An easy way to change the character is in PasswordBox. But it does not have the ability to disable masking and additional code must be used to bind Password. At the moment, we have to use a solution in which a TextBox is used in the “without masking” mode, and a PasswordBox in the “with masking” mode.
Can you recommend something more optimal?
I think a good and simple solution is to use an adorner to render the masking symbols as an overlay of the original input.
Show the adorner to render the masking characters while hiding the password by setting the foreground brush to the background brush.
The following example shows how to use an
Adornerto decorate theTextBox. I have removed some code to reduce the complexity (the original library code also contained validation of input characters and password length, event logic, routed commands,SecureStringsupport, low-level caret positioning to support any font family for those cases where the font is not a monospace font and password characters and masking characters won't align correctly etc. and a much more complex defaultControlTemplate). The current version therefore only supports monospace fonts. The supported fonts have to be registered in the constructor. You could implement monospace font detection instead.However, it's a fully working example (happy easter!).
UnsecurePasswodBox.cs
Generic.xaml