How to bind to a PasswordBox in MVVM

前端 未结 30 2117
执念已碎
执念已碎 2020-11-22 11:50

I have come across a problem with binding to a PasswordBox. It seems it\'s a security risk but I am using the MVVM pattern so I wish to bypass this. I found som

30条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 12:39

    As mentioned before VM should be unaware of the View but passing whole PasswordBox looks like the simplest approach. So maybe instead of casting passed parameter to PasswordBox use Reflection to extract Password property from it. In this case VM expects some kind of Password Container with property Password(I'm ussing RelayCommands from MVMM Light-Toolkit):

    public RelayCommand SignIn
    {
        get
        {
            if (this.signIn == null)
            {
                this.signIn = new RelayCommand((passwordContainer) => 
                    {
                        var password = passwordContainer.GetType().GetProperty("Password").GetValue(passwordContainer) as string;
                        this.authenticationService.Authenticate(this.Login, password);
                    });
            }
    
            return this.signIn;
        }
    }
    
    
    

    It can be easily tested with anonymous class:

    var passwordContainer = new
        {
            Password = "password"
        };
    

    提交回复
    热议问题