wpf - 从PasswordBox获取密码

标签 wpf mvvm passwordbox securestring

我在 SO 上找到了有关此问题的一些信息,但不知何故我并没有真正理解;-)从我所读到的内容来看,由于安全原因,PasswordBox 的密码不能绑定(bind)到属性,即保留内存中的明文密码。

我的模型包含这个:

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

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

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

最佳答案

因此,我编写了一个带有可绑定(bind)密码-SecureStringUserControl。这个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>

关于wpf - 从PasswordBox获取密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13513472/

相关文章:

c# - 如何将插入符号位置设置为 WPF 密码框中的特定索引

wpf - ESRI ArcGIS : Map. 缩小()

c# - 单击按钮后更改按钮的效果 WPF

c# - WPF 中是否有类似 Winforms.Show ( IWin32Window 所有者)的方法?

c# - 扩展的WPF工具包-WatermarkPasswordBox防止输入回车值

c# - 将 Entry TextChanged 绑定(bind)到 Xamarin.Forms 中按钮命令的 CanExecute 方法

html - 如何固定密码输入字段的大小?

c# - 如何覆盖字典的 ToString()

c# - 使用 MVVM 在代码中动态设置资源

.net - 为什么PasswordBox控件会使WPF应用程序崩溃?