在 WPF 中使用 PasswordBox - MVVM [英] Using PasswordBox with WPF - MVVM

查看:105
本文介绍了在 WPF 中使用 PasswordBox - MVVM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了几篇关于如何使用附加属性绑定到 WPF 中 PasswordBox 的值的文章.但是,每篇文章还引用了 .NET 文档,该文档解释了为什么 PasswordBox 一开始就不能绑定.

I've read several articles about how to use Attached Properties to bind to the value of a PasswordBox in WPF. However, every article also references the .NET documentation which explains why the PasswordBox was not made bindable in the first place.

我无论如何都不认为自己是安全专家,但我认为 Microsoft 的某个人知道他们在做什么,我不应该付出努力试图撤消它.

I do not consider myself a security expert by any means, but I figure that someone at Microsoft knew what they were doing, and I shouldn't be putting forth the effort trying to undo it.

所以,我想出了自己的解决方案.

So, instead, I came up with my own solution.

public class LoginViewModel
{
   // other properties here

   public PasswordBox Password
   {
      get { return m_passwordBox; }
   }

   // Executed when the Login button is clicked.
   private void LoginExecute()
   {
      var password = Password.SecurePassword;

      // do more stuff...
   }
}

然后,在我的 XAML 中,我只是通过将 Password 字段绑定到 ContentPresenter 来呈现 PasswordBox.

Then, in my XAML, I just render the PasswordBox by binding the Password field to a ContentPresenter.

所以我的问题是……这样做有问题吗?我意识到通过让实际控件出现在我的 ViewModel 中,我在某种程度上破坏了 MVVM,但至少这似乎比不保护密码字段更正确.

So my question is... is there a problem with doing it this way? I realize that I'm sort of breaking the MVVM in a way by letting actual controls appear in my ViewModel, but at least this seems more correct than just un-securing the password field.

如果这实际上是一个问题,有没有人想出不涉及使用附加属性并将密码存储在 ViewModel 中的解决方案?

If this is, in fact, a problem, has anyone come up with a solution that doesn't involve using Attached Properties and storing the password in the ViewModel?

谢谢!-J

推荐答案

至少在登录期间需要密码时将密码存储在 VM 中有什么问题?您是正确的,根据 MVVM 模式,VM 不应该引用像 PasswordBox 这样的控件.

What is wrong with storing the password in the VM at least while it is needed during login? You are correct that according to MVVM pattern the VM should not have a reference to a control like a PasswordBox.

在视图中,为 PasswordChanged 事件添加一个处理程序.在处理程序中,使用密码框的 SecurePassword 更新 VM 中的 SecureString 属性.

In the view, add a handler to the PasswordChanged event. In the handler, update a SecureString property in the VM with the SecurePassword of the passwordbox.

这篇关于在 WPF 中使用 PasswordBox - MVVM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆