Is it a bad idea to bind PasswordBox password?

后端 未结 2 1892
忘掉有多难
忘掉有多难 2021-01-02 02:04

I\'ve read that the password in a WPF PasswordBox does not have a dependency property for binding the password for security reasons. Despite this, there are ways to

2条回答
  •  庸人自扰
    2021-01-02 02:40

    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 object to your PasswordBox object like below:

    public sealed class PasswordBoxBehavior : Behavior
    {
        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:

    
        ...
        
            
                
              
        
        ...
    
    

提交回复
热议问题