How to bind to a PasswordBox in MVVM

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

    To solve the OP problem without breaking the MVVM, I would use custom value converter and a wrapper for the value (the password) that has to be retrieved from the password box.

    public interface IWrappedParameter
    {
        T Value { get; }
    }
    
    public class PasswordBoxWrapper : IWrappedParameter
    {
        private readonly PasswordBox _source;
    
        public string Value
        {
            get { return _source != null ? _source.Password : string.Empty; }
        }
    
        public PasswordBoxWrapper(PasswordBox source)
        {
            _source = source;
        }
    }
    
    public class PasswordBoxConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // Implement type and value check here...
            return new PasswordBoxWrapper((PasswordBox)value);
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new InvalidOperationException("No conversion.");
        }
    }
    

    In the view model:

    public string Username { get; set; }
    
    public ICommand LoginCommand
    {
        get
        {
            return new RelayCommand>(password => { Login(Username, password); });
        }
    }
    
    private void Login(string username, string password)
    {
        // Perform login here...
    }
    

    Because the view model uses IWrappedParameter, it does not need to have any knowledge about PasswordBoxWrapper nor PasswordBoxConverter. This way you can isolate the PasswordBox object from the view model and not break the MVVM pattern.

    In the view:

    
        
    
    ...
    
    

提交回复
热议问题