How to bind to a PasswordBox in MVVM

前端 未结 30 2360
执念已碎
执念已碎 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:38

    My 2 cents:

    I developed once a typical login dialog (user and password boxes, plus "Ok" button) using WPF and MVVM. I solved the password binding issue by simply passing the PasswordBox control itself as a parameter to the command attached to the "Ok" button. So in the view I had:

    
    

    And in the ViewModel, the Execute method of the attached command was as follows:

    void Execute(object parameter)
    {
        var passwordBox = parameter as PasswordBox;
        var password = passwordBox.Password;
        //Now go ahead and check the user name and password
    }
    

    This slightly violates the MVVM pattern since now the ViewModel knows something about how the View is implemented, but in that particular project I could afford it. Hope it is useful for someone as well.

提交回复
热议问题