How to bind to a PasswordBox in MVVM

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

    While I agree it's important to avoid storing the password anywhere, I still need the ability to instantiate the view model without a view and execute my tests against it.

    The solution that worked for me was to register the PasswordBox.Password function with the view model, and have the view model invoke it when executing the login code.

    This does mean a line of code in the view's codebehind.

    So, in my Login.xaml I have

    
    

    and in Login.xaml.cs I have

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

    then in LoginViewModel.cs I have the PasswordHandler defined

    public Func PasswordHandler { get; set; }
    

    and when login needs to happen the code invokes the handler to get the password from the view...

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

    This way, when I want to test the viewmodel I can simply set PasswordHandler to an anonymous method that lets me deliver whatever password I want to use in the test.

提交回复
热议问题