从PasswordBox获取密码

时间:2012-11-22 13:12:01

标签: wpf mvvm passwordbox securestring

我已经在SO上找到了关于这个问题的几个信息,但不知怎的,我真的没有得到它;-)从我所看到的,由于安全原因,PasswordBox的密码不能绑定到属性,即保持内存中的普通密码。

我的模型包含:

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

虽然不支持绑定到PasswordBox的数据,但Microsoft必须一些想法如何从PasswordBox获取密码并以安全的方式使用它,是吗?

这可能是一种适当且相对简单的方法吗?

2 个答案:

答案 0 :(得分:1)

因此,我写了一个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>

答案 1 :(得分:-1)

<PasswordBox Height="29" HorizontalAlignment="Left" Margin="191,136,0,0" Name="textPassword" VerticalAlignment="Top" PasswordChar="*" Width="167" />

密码箱名称为textPassword

String pass = textPassword.Password;