2

我在 SO 找到了关于这个问题的一些信息,但不知何故我并没有真正得到它;-) 根据我的阅读,由于安全原因,PasswordBox 的密码不能绑定到属性,即保留纯密码在记忆中。

我的模型包含这个:

private SecureString password;
public SecureString Password {
  get { return password; }
  set { password = value; }
}

虽然不支持将数据绑定到 PasswordBox,但Microsoft 必须知道如何从 PasswordBox 获取密码并以安全的方式使用它,嗯?

什么是合适且相对简单的方法?

4

2 回答 2

2

因此,我写了一个UserControl带有可绑定密码的 - SecureString。这个代码UserControl看起来像:

代码隐藏:

public partial class BindablePasswordBox : UserControl
    {
        public static readonly DependencyProperty SecurePasswordProperty = DependencyProperty.Register(
           "SecurePassword", typeof(SecureString), typeof(BindablePasswordBox), new PropertyMetadata(default(SecureString)));

        public SecureString SecurePassword
        {
            get { return (SecureString)GetValue(SecurePasswordProperty); }
            set { SetValue(SecurePasswordProperty, value); }
        }

        public BindablePasswordBox()
        {
            InitializeComponent();
        }

        private void PasswordBox_OnPasswordChanged(object sender, RoutedEventArgs e)
        {
            SecurePassword = ((PasswordBox)sender).SecurePassword;
        }

        private void BindablePasswordBox_OnGotFocus(object sender, RoutedEventArgs e)
        {
            passwordBox.Focus();
        }
    }

XAML:

<UserControl x:Class="Sol.Controls.BindablePasswordBox"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"
             GotFocus="BindablePasswordBox_OnGotFocus">
    <PasswordBox x:Name="passwordBox" PasswordChanged="PasswordBox_OnPasswordChanged"/>
</UserControl>
于 2014-10-07T10:02:56.880 回答
0
<PasswordBox Height="29" HorizontalAlignment="Left" Margin="191,136,0,0" Name="textPassword" VerticalAlignment="Top" PasswordChar="*" Width="167" />

密码箱的名称是textPassword

String pass = textPassword.Password;
于 2014-10-07T09:54:33.293 回答