WPF控件:密码框绑定MVVM

以下是一种使用 MVVM 模式的方法:

  1. 首先,在 ViewModel 中添加一个属性来保存密码,我们可以使用 SecureString 类型。
 // 密码变量
 private SecureString _password;

 // 密码属性,用于获取和设置密码
 public SecureString Password
 {
     get
     {
         return _password;
     }
     set
     {
         // 如果新值与旧值不同
         if (_password != value)
         {
             // 更新密码
             _password = value;
             // 触发属性更改通知,通知UI层密码已更改
             RaisePropertyChanged(nameof(Password));
         }
     }
 }

 

  1. 创建一个附加属性来处理 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;
      }
  }

 

  1. 在 XAML 中,使用行为触发器来触发命令。
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
<PasswordBox
    x:Name="PasswordBox"
    Height="45"
    Margin="5"
    FontSize="20"
    FontWeight="Thin">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="PasswordChanged">
            <i:InvokeCommandAction Command="{Binding PasswordChangedCommand}" CommandParameter="{Binding ElementName=PasswordBox}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</PasswordBox>
  1. 查看密码框的内容。
MessageBox.Show(SecureStringToString(Password));
/// <summary>
/// 将 SecureString 类型的数据转换为普通的字符串类型。
/// </summary>
/// <param name="secureString">要转换的 SecureString 对象。</param>
/// <returns>转换后的字符串,如果转换失败则返回空字符串。</returns>
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);
        }
    }
}

 

 

 

posted @ 2024-04-24 22:32  Windows窗  阅读(275)  评论(2编辑  收藏  举报