How to bind to a PasswordBox in MVVM

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

    A simple solution without violating the MVVM pattern is to introduce an event (or delegate) in the ViewModel that harvests the password.

    In the ViewModel:

    public event EventHandler HarvestPassword;

    with these EventArgs:

    class HarvestPasswordEventArgs : EventArgs
    {
        public string Password;
    }
    

    in the View, subscribe to the event on creating the ViewModel and fill in the password value.

    _viewModel.HarvestPassword += (sender, args) => 
        args.Password = passwordBox1.Password;
    

    In the ViewModel, when you need the password, you can fire the event and harvest the password from there:

    if (HarvestPassword == null)
      //bah 
      return;
    
    var pwargs = new HarvestPasswordEventArgs();
    HarvestPassword(this, pwargs);
    
    LoginHelpers.Login(Username, pwargs.Password);
    

提交回复
热议问题