The password property of PasswordBox in WPF does not support data binding (for security reasons) and is required in the MVVM design pattern.
So we're going to add a helper class to complete the binding.
Code Transfer from: http://blog.csdn.net/oyi319/article/details/6551532
/// <summary> ///to increase the binding function for the password of the PasswordBox control/// </summary> Public Static classPasswordboxhelper { Public Static ReadOnlyDependencyProperty Passwordproperty =dependencyproperty.registerattached ("Password", typeof(string),typeof(passwordboxhelper),NewFrameworkpropertymetadata (string. Empty, onpasswordpropertychanged)); Public Static ReadOnlyDependencyProperty Attachproperty =dependencyproperty.registerattached ("Attach", typeof(BOOL),typeof(Passwordboxhelper),NewPropertyMetadata (false, Attach)); Private Static ReadOnlyDependencyProperty Isupdatingproperty =dependencyproperty.registerattached ("isupdating",typeof(BOOL), typeof(Passwordboxhelper)); Public Static voidSetattach (DependencyObject DP,BOOLvalue) {DP. SetValue (attachproperty, value); } Public Static BOOLGetattach (DependencyObject dp) {return(BOOL) DP. GetValue (Attachproperty); } Public Static stringGetPassword (DependencyObject dp) {return(string) DP. GetValue (Passwordproperty); } Public Static voidSetPassword (DependencyObject DP,stringvalue) {DP. SetValue (passwordproperty, value); } Private Static BOOLgetisupdating (DependencyObject dp) {return(BOOL) DP. GetValue (Isupdatingproperty); } Private Static voidSetisupdating (DependencyObject DP,BOOLvalue) {DP. SetValue (isupdatingproperty, value); } Private Static voidonpasswordpropertychanged (DependencyObject sender, DependencyPropertyChangedEventArgs e) { PasswordBox PasswordBox= Sender asPasswordBox; Passwordbox.passwordchanged-=passwordchanged; if(! (BOOL) getisupdating (PasswordBox)) {Passwordbox.password= (string) E.newvalue; } passwordbox.passwordchanged+=passwordchanged; } Private Static voidAttach (DependencyObject sender, DependencyPropertyChangedEventArgs e) {passwordbo X PasswordBox= Sender asPasswordBox; if(PasswordBox = =NULL) return; if((BOOL) {e.oldvalue) {passwordbox.passwordchanged-=passwordchanged; } if((BOOL) {e.newvalue) {passwordbox.passwordchanged+=passwordchanged; } } Private Static voidPasswordChanged (Objectsender, RoutedEventArgs e) {PasswordBox PasswordBox= Sender asPasswordBox; Setisupdating (PasswordBox,true); SetPassword (PasswordBox, Passwordbox.password); Setisupdating (PasswordBox,false); } }
Then PasswordBox can do the following bindings in Xmal
<heplers:PasswordBoxHelper.Attach= "True" heplers: Passwordboxhelper.password= "{Binding path=password,mode=twoway,updatesourcetrigger= PropertyChanged}"/>
Data binding for PasswordBox in WPF