【问题标题】:Getting password from PasswordBox从 PasswordBox 获取密码
【发布时间】:2012-11-22 13:12:01
【问题描述】:

我在 SO 找到了关于这个问题的一些信息,但不知何故我并没有真正得到它;-) 从我所读到的内容来看,由于安全原因,PasswordBox 的密码不能绑定到属性,即保留内存中的普通密码。

我的模型包含这个:

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

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

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

【问题讨论】:

标签: wpf mvvm passwordbox securestring


【解决方案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>

【讨论】:

    【解决方案2】:
    <PasswordBox Height="29" HorizontalAlignment="Left" Margin="191,136,0,0" Name="textPassword" VerticalAlignment="Top" PasswordChar="*" Width="167" />
    

    密码箱名称为textPassword:

    String pass = textPassword.Password;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-19
      • 1970-01-01
      相关资源
      最近更新 更多