wpf 从 PasswordBox 获取密码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13513472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting password from PasswordBox
提问by Robert Strauch
I have found several information on this issue here at SO but somehow I'm not really getting it ;-) From what I have read, the password of a PasswordBox cannot be bound to a property due to security reasons, i.e. keeping the plain password in memory.
我在 SO 上找到了一些关于这个问题的信息,但不知何故我并没有真正得到它;-) 从我读到的内容来看,出于安全原因,PasswordBox 的密码不能绑定到属性,即保留普通密码在记忆中。
My model contains this:
我的模型包含这个:
private SecureString password;
public SecureString Password {
get { return password; }
set { password = value; }
}
Though data binding to a PasswordBox is not supported, Microsoft must have someidea how to get the password from the PasswordBox and use it in a secure way, eh?
虽然数据绑定到PasswordBox不支持,微软必须有一些想法如何从PasswordBox得到密码,并以安全的方式使用它,是吗?
What could be an appropriate and relatively easy way to do so?
什么是适当且相对简单的方法?
回答by Tomtom
Therefor I have written a UserControlwith a bindable Password-SecureString. The code of this UserControllooks like:
因此,我编写了一个UserControl带有可绑定密码的SecureString. 这段代码UserControl看起来像:
Code-Behind:
代码隐藏:
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:
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>
回答by Abhiram Padhi
<PasswordBox Height="29" HorizontalAlignment="Left" Margin="191,136,0,0" Name="textPassword" VerticalAlignment="Top" PasswordChar="*" Width="167" />
Name of passwordbox is textPassword:
密码箱的名称是textPassword:
String pass = textPassword.Password;

