Is it a bad idea to bind PasswordBox password?

后端 未结 2 1887
忘掉有多难
忘掉有多难 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:24

    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![enter image description here]1

    0 讨论(0)
  • 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<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>
    
    0 讨论(0)
提交回复
热议问题