Is it a bad idea to bind PasswordBox password?
Using tools like WPF Inspector or Snoop you can spy the password string. An alternative to passing the PasswordBox to the view-model is to attach a Behavior<UIElement> object to your PasswordBox object like below:
public sealed class PasswordBoxBehavior : Behavior<UIElement>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.LostKeyboardFocus += AssociatedObjectLostKeyboardFocus;
}
protected override void OnDetaching()
{
AssociatedObject.LostKeyboardFocus -= AssociatedObjectLostKeyboardFocus;
base.OnDetaching();
}
void AssociatedObjectLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
var associatedPasswordBox = AssociatedObject as PasswordBox;
if (associatedPasswordBox != null)
{
// Set your view-model's Password property here
}
}
}
and the XAML code:
<Window ...
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity">
...
<PasswordBox ....>
<i:Interaction.Behaviors>
<local:PasswordBoxBehavior />
</i:Interaction.Behaviors>
</PasswordBox>
...
</Window>
Not binding the password box thinking snooping it will not yield the results is not wise to think!.
Passwordbox.Password will still show the password no matter what]1