WPF

Why WPF PasswordBox.Password cannot be bound, and two ways to hand it to a ViewModel

S. Iguchi WPF Notes s-iguchi
WPF

PasswordBox.Password is not a dependency property, so binding it in XAML throws. After confirming the cause from the exception and the type metadata, the article compares an attached property with passing the control as a CommandParameter, looking at button state and plaintext left in memory.

Key points

  • PasswordBox is sealed, so no derived class can add a dependency property; PasswordChanged is the only observation hook.
  • Subscribing to PasswordChanged inside the change callback misses input when the ViewModel starts with an empty string, since the effective value never changes.
  • Writing the same value back to Password on every keystroke moves the caret to the start, so typing "abc" arrives as "cba".
  • A separate Attach property plus BindsTwoWayByDefault on BoundPassword syncs input correctly when the value is compared first.
  • Binding CommandParameter to Password or SecurePassword passes an empty value; passing the PasswordBox itself gives the command the typed length.
  • A process memory scan found the password after one string read of Password, but not after SecureString reads or ZeroFreeGlobalAllocUnicode.

Real-world use

  • A WPF MVVM sign-in screen that authenticates with a username and password
  • A login form that must keep the sign-in button disabled while the password is empty
  • An authentication flow that clears the password field after a failed sign-in
  • A security-sensitive desktop app that does not want the password held as a string on the ViewModel

This summary was generated by the agent from the original post on S. Iguchi WPF Notes. The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message