首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从PasswordBox获取密码

从PasswordBox获取密码
EN

Stack Overflow用户
提问于 2012-11-22 13:12:01
回答 2查看 11.6K关注 0票数 2

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

我的模型包含以下内容:

代码语言:javascript
复制
private SecureString password;
public SecureString Password {
  get { return password; }
  set { password = value; }
}

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

有什么合适的、相对容易的方法来做到这一点?

EN

回答 2

Stack Overflow用户

发布于 2014-10-07 10:02:56

为此,我编写了一个具有可绑定密码的UserControl -SecureString。此UserControl的代码如下所示:

代码-隐藏:

代码语言:javascript
复制
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:

代码语言:javascript
复制
<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
EN

Stack Overflow用户

发布于 2014-10-07 09:54:33

代码语言:javascript
复制
<PasswordBox Height="29" HorizontalAlignment="Left" Margin="191,136,0,0" Name="textPassword" VerticalAlignment="Top" PasswordChar="*" Width="167" />

passwordbox的名称是textPassword

代码语言:javascript
复制
String pass = textPassword.Password;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13513472

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档