在C# WPF中实现PasswordBox的MVVM绑定,并确保在焦点离开时才更新数据,确实需要一些特殊的处理,因为PasswordBox控件本身并不直接支持双向数据绑定。本文采用创建 PasswordHelper 附加属性类来实现
public static class PasswordHelper
{
public static readonly DependencyProperty PasswordProperty =
DependencyProperty.RegisterAttached(
"Password",
typeof(string),
typeof(PasswordHelper),
new PropertyMetadata(string.Empty, OnPasswordPropertyChanged)
);
public static string GetPassword(DependencyObject PasswordObject)
{
return (string)PasswordObject.GetValue(PasswordProperty);
}
public static void SetPassword(DependencyObject PasswordObject, string PasswordValue)
{
PasswordObject.SetValue(PasswordProperty, PasswordValue);
}
private static void OnPasswordPropertyChanged(DependencyObject PasswordObject, DependencyPropertyChangedEventArgs Password)
{
PasswordBox PasswordBox = (PasswordBox)PasswordObject;
PasswordBox.LostFocus -= PasswordChanged;
PasswordBox.Password = Password.NewValue.ToString();
PasswordBox.LostFocus += PasswordChanged;
}
private static void PasswordChanged(object PasswordObject, RoutedEventArgs _)
{
SetPassword((PasswordBox)PasswordObject, ((PasswordBox)PasswordObject).Password);
}
}
引入命名空间 xmlns:Common=“clr-namespace:命名空间名”
<PasswordBox
Common:PasswordHelper.Password="{Binding V.ButtonName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>