PasswordBox and MVVM

后端 未结 5 1626
再見小時候
再見小時候 2021-02-02 13:35

We have the following scenario:

  1. MVVM userinterface where a user can place his password (actually a PasswordBox)
  2. Server that shall do some wor
5条回答
  •  渐次进展
    2021-02-02 14:13

    I have solved this problem by creating a UserControl that exposes a SecureString dependency property that can be bound to. This method keeps the password in a SecureString at all times, and doesn't "break" MVVM.

    UserControl

    XAML

    
               
            
        
    
    

    CS

    public partial class PasswordUserControl : UserControl
    {
        public SecureString Password
        {
            get { return (SecureString) GetValue(PasswordProperty); }
            set { SetValue(PasswordProperty, value); }
        }
        public static readonly DependencyProperty PasswordProperty =
            DependencyProperty.Register("Password", typeof(SecureString), typeof(UserCredentialsInputControl),
                new PropertyMetadata(default(SecureString)));
    
    
        public PasswordUserControl()
        {
            InitializeComponent();
    
            // Update DependencyProperty whenever the password changes
            PasswordBox.PasswordChanged += (sender, args) => {
                Password = ((PasswordBox) sender).SecurePassword;
            };
        }
    }
    

    Example usage

    Using the control is very straightforward, just bind the password DependencyProperty on the control to a Password property on your ViewModel. The ViewModel's Password property should be a SecureString.

    
    

    Change the Mode and UpdateSource trigger on the binding to whatever is best for you.

    If you need the password in plain text, the following page describes the proper way to convert between SecureString and string: http://blogs.msdn.com/b/fpintos/archive/2009/06/12/how-to-properly-convert-securestring-to-string.aspx. Of course you shouldn't store the plain text string...

提交回复
热议问题