我已经通过创建一个公开SecureString依赖属性的UserControl来解决了这个问题,可以进行绑定。 这种方法始终将密码保存在SecureString中,并且不会“破坏”MVVM。
UserControl
XAML
<UserControl x:Class="Example.PasswordUserControl"
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">
<Grid>
<PasswordBox Name="PasswordBox" />
</Grid>
</UserControl>
CS
public partial class PasswordUserControl : UserControl
{
public SecureString Password
{
get { return (SecureString) GetValue(PasswordProperty); }
set { SetValue(PasswordProperty, value); }
}
public static readonly DependencyProperty PasswordProperty =
DependencyProperty.Register("Password", typeof(SecureString), typeof(UserCredentialsInputControl),
new PropertyMetadata(default(SecureString)));
public PasswordUserControl()
{
InitializeComponent();
PasswordBox.PasswordChanged += (sender, args) => {
Password = ((PasswordBox) sender).SecurePassword;
};
}
}
示例用法
使用该控件非常简单,只需将控件上的密码DependencyProperty绑定到ViewModel上的Password属性即可。ViewModel的Password属性应为SecureString类型。
<controls:PasswordUserControl Password="{Binding Password, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
根据您的需要,更改绑定上的模式和UpdateSource触发器。
如果您需要以明文形式获取密码,请参考以下页面描述将SecureString和string之间进行正确转换的方法:http://blogs.msdn.com/b/fpintos/archive/2009/06/12/how-to-properly-convert-securestring-to-string.aspx。当然您不应该存储明文字符串...
PasswordBox.Password
,然后将用户名和加密后的密码传递给服务器,而不是将未加密的PasswordBox
对象传递给服务器。PasswordBox.Password
是明文,所以我不喜欢将PasswordBox
对象保留更长时间。 - Rachel