我遇到了绑定到密码盒的问题。这似乎是一个安全风险,但我正在使用MVVM模式,所以我希望绕过这个。我在这里发现了一些有趣的代码(有人使用过这个或类似的代码吗?)

http://www.wpftutorial.net/PasswordBox.html

从技术上讲,它看起来很棒,但我不确定如何检索密码。

我基本上有属性在我的LoginViewModel用户名和密码。用户名是好的,正在工作,因为它是一个文本框。

我使用上面的代码,并输入这个

<PasswordBox ff:PasswordHelper.Attach="True"
    ff:PasswordHelper.Password="{Binding Path=Password}" Width="130"/>

当我有PasswordBox作为一个文本框和绑定路径=密码,然后在我的LoginViewModel属性更新。

我的代码非常简单,基本上我有一个命令为我的按钮。当我按下它CanLogin被调用,如果它返回真,它调用Login。 你可以看到,我检查了我的用户名属性,这很好。

在登录我发送到我的服务的用户名和密码,用户名包含数据从我的视图,但密码是空|空

private DelegateCommand loginCommand;

public string Username { get; set; }
public string Password { get; set; }


public ICommand LoginCommand
{
    get
    {
        if (loginCommand == null)
        {
            loginCommand = new DelegateCommand(
                Login, CanLogin );
        }
        return loginCommand;
    }
}

private bool CanLogin()
{
    return !string.IsNullOrEmpty(Username);
}

private void Login()
{
    bool result = securityService.IsValidLogin(Username, Password);

    if (result) { }
    else { }
}

这就是我正在做的

<TextBox Text="{Binding Path=Username, UpdateSourceTrigger=PropertyChanged}"
         MinWidth="180" />

<PasswordBox ff:PasswordHelper.Attach="True" 
             ff:PasswordHelper.Password="{Binding Path=Password}" Width="130"/>

我有我的文本框,这是没有问题的,但在我的ViewModel密码是空的。

是我做错了什么还是漏了一步?

我放了一个断点,果然代码进入静态助手类,但它从不更新我的ViewModel中的密码。


当前回答

对我来说,这两件事都不对:

实现明文密码属性 将PasswordBox作为命令参数发送给ViewModel

像Steve在CO中描述的那样传输SecurePassword (SecureString实例)似乎是可以接受的。我更喜欢行为而不是背后的代码,而且我还需要能够从视图模型重置密码。

Xaml (Password是ViewModel属性):

<PasswordBox>
    <i:Interaction.Behaviors>
        <behaviors:PasswordBinding BoundPassword="{Binding Password, Mode=TwoWay}" />
    </i:Interaction.Behaviors>
</PasswordBox>

行为:

using System.Security;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace Evidence.OutlookIntegration.AddinLogic.Behaviors
{
    /// <summary>
    /// Intermediate class that handles password box binding (which is not possible directly).
    /// </summary>
    public class PasswordBoxBindingBehavior : Behavior<PasswordBox>
    {
        // BoundPassword
        public SecureString BoundPassword { get { return (SecureString)GetValue(BoundPasswordProperty); } set { SetValue(BoundPasswordProperty, value); } }
        public static readonly DependencyProperty BoundPasswordProperty = DependencyProperty.Register("BoundPassword", typeof(SecureString), typeof(PasswordBoxBindingBehavior), new FrameworkPropertyMetadata(OnBoundPasswordChanged));

        protected override void OnAttached()
        {
            this.AssociatedObject.PasswordChanged += AssociatedObjectOnPasswordChanged;
            base.OnAttached();
        }

        /// <summary>
        /// Link up the intermediate SecureString (BoundPassword) to the UI instance
        /// </summary>
        private void AssociatedObjectOnPasswordChanged(object s, RoutedEventArgs e)
        {
            this.BoundPassword = this.AssociatedObject.SecurePassword;
        }

        /// <summary>
        /// Reacts to password reset on viewmodel (ViewModel.Password = new SecureString())
        /// </summary>
        private static void OnBoundPasswordChanged(object s, DependencyPropertyChangedEventArgs e)
        {
            var box = ((PasswordBoxBindingBehavior)s).AssociatedObject;
            if (box != null)
            {
                if (((SecureString)e.NewValue).Length == 0)
                    box.Password = string.Empty;
            }
        }

    }
}

其他回答

我使用的是简洁的mvvm友好的解决方案,还没有提到。首先,我在XAML中命名PasswordBox:

<PasswordBox x:Name="Password" />

然后我在视图构造函数中添加了一个方法调用:

public LoginWindow()
{
    InitializeComponent();
    ExposeControl<LoginViewModel>.Expose(this, view => view.Password,
        (model, box) => model.SetPasswordBox(box));
}

就是这样。当视图模型通过DataContext附加到视图时,它将收到通知,当它被分离时,它将收到另一个通知。此通知的内容可以通过lambdas进行配置,但通常它只是视图模型上的setter或方法调用,将有问题的控件作为参数传递。

通过使用视图公开接口而不是子控件,可以很容易地使它对mvvm友好。

上面的代码依赖于我博客上发布的helper类。

虽然我同意避免将密码存储在任何地方很重要,但我仍然需要能够在没有视图的情况下实例化视图模型,并针对它执行测试。

对我来说,有效的解决方案是注册PasswordBox。Password函数,并让视图模型在执行登录代码时调用它。

这意味着视图隐藏代码中的一行代码。

在我的Login中。xaml我有

<PasswordBox x:Name="PasswordBox"/>

在Login.xaml.cs中

LoginViewModel.PasswordHandler = () => PasswordBox.Password;

然后在LoginViewModel.cs我有PasswordHandler定义

public Func<string> PasswordHandler { get; set; }

当需要登录时,代码调用处理程序从视图中获取密码…

bool loginResult = Login(Username, PasswordHandler());

这样,当我想要测试视图模型时,我可以简单地将PasswordHandler设置为一个匿名方法,让我在测试中交付我想要使用的任何密码。

我使用了一个身份验证检查,然后是一个中介类向View调用的子(它也实现了身份验证检查),将密码写入数据类。

这不是一个完美的解决方案;但是,它弥补了我无法移动密码的问题。

这很简单。为password创建另一个属性,并将其与TextBox绑定

但所有输入操作都使用实际的密码属性执行

private string _Password;

    public string PasswordChar
    {
        get
        {
            string szChar = "";

            foreach(char szCahr in _Password)
            {
                szChar = szChar + "*";
            }

            return szChar;
        }

        set
        {
            _PasswordChar = value; NotifyPropertyChanged();
        }
    }

public string密码 { 得到 { 返回_Password; }

        set
        {
            _Password = value; NotifyPropertyChanged();
            PasswordChar = _Password;
        }
    }

正如你所看到的,我绑定到密码,但也许它绑定到静态类..

它是一个附加属性。这种属性可以应用于任何类型的DependencyObject,而不仅仅是声明它的类型。因此,尽管它是在PasswordHelper静态类中声明的,但它还是应用于使用它的PasswordBox。

要使用这个附加属性,你只需要将它绑定到ViewModel中的Password属性:

<PasswordBox w:PasswordHelper.Attach="True" 
         w:PasswordHelper.Password="{Binding Password}"/>