以下是一种使用 MVVM 模式的方法:
- 首先,在 ViewModel 中添加一个属性来保存密码,我们可以使用 SecureString 类型。
// 密码变量private SecureString \_password;// 密码属性,用于获取和设置密码public SecureString Password{get{return \_password;}set{// 如果新值与旧值不同if (\_password != value){// 更新密码\_password = value;// 触发属性更改通知,通知UI层密码已更改RaisePropertyChanged(nameof(Password));}}}
- 创建一个附加属性来处理 PasswordBox 的密码变化,并将其绑定到 ViewModel 中的命令。
public ICommand PasswordChangedCommand => new DelegateCommand<object>(PasswordChanged);private void PasswordChanged(object parameter){var passwordBox = parameter as PasswordBox;if (passwordBox != null){// 设置 ViewModel 中的密码属性Password = passwordBox.SecurePassword;}}
- 在 XAML 中,使用行为触发器来触发命令。
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
<PasswordBoxx:Name="PasswordBox"Height="45"Margin="5"FontSize="20"FontWeight="Thin">"PasswordChanged">"{Binding PasswordChangedCommand}" CommandParameter="{Binding ElementName=PasswordBox}" />
- 查看密码框的内容。
MessageBox.Show(SecureStringToString(Password));
///
/// 将 SecureString 类型的数据转换为普通的字符串类型。
///
/// 要转换的 SecureString 对象。
/// 转换后的字符串,如果转换失败则返回空字符串。
private string SecureStringToString(SecureString secureString)
{// 初始化指针IntPtr ptr = IntPtr.Zero;try{// 将 SecureString 转换为指针ptr = Marshal.SecureStringToGlobalAllocUnicode(secureString);if (ptr != IntPtr.Zero){// 将指针中的数据复制到一个普通的字符串return Marshal.PtrToStringUni(ptr);}else{return string.Empty;}}catch (Exception ex){// 处理异常Console.WriteLine($"转换 SecureString 出错:{ex.Message}");return string.Empty;}finally{// 清除内存中的敏感数据if (ptr != IntPtr.Zero){Marshal.ZeroFreeGlobalAllocUnicode(ptr);}}
}