我通过创建一个公开可以绑定的 SecureString 依赖属性的 UserControl 解决了这个问题。此方法始终将密码保存在 SecureString 中,并且不会“破坏” MVVM。
用户控制
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();
        // Update DependencyProperty whenever the password changes
        PasswordBox.PasswordChanged += (sender, args) => {
            Password = ((PasswordBox) sender).SecurePassword;
        };
    }
}
示例用法
使用控件非常简单,只需将控件上的密码 DependencyProperty 绑定到 ViewModel 上的密码属性即可。ViewModel 的 Password 属性应该是 SecureString。
<controls:PasswordUserControl Password="{Binding Password, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
将绑定上的 Mode 和 UpdateSource 触发器更改为最适合您的。
如果您需要纯文本密码,以下页面描述了在 SecureString 和字符串之间转换的正确方法:http: //blogs.msdn.com/b/fpintos/archive/2009/06/12/how-to-properly -convert-securestring-to-string.aspx。当然你不应该存储纯文本字符串......