我想将 User.Password 属性绑定到 PasswordBox (TwoWay)。由于 PasswordBox.Password 不可绑定,因此我制作了 AttachedProperties 来解决此问题(一个用于激活绑定,一个用于保存实际密码)。问题是它们不会绑定(GetBindingExpression 返回 null)。
还:
- AttachedProperties 工作。如果我在 PasswordBox 中键入,Password 和 PasswordValue(附加属性)设置正确,但 User.Password 保持为空。
- 绑定 AttachedProperty 也可以,但只能反过来:如果我将 PasswordValue 绑定到 TextBlock(TextBlock.Text 是目标,helper:PasswordValue 是源),它就可以工作。只有我不能使用它,因为 User 的属性不是依赖对象。
- User.Password 是可绑定的(用户实现 INotifyPropertyChanged),我设法将 User.Username 绑定到 TextBox.Text 和(用户名和密码是相似的字符串属性)
以下是附加属性:
public static bool GetTurnOnBinding(DependencyObject obj)
{
return (bool)obj.GetValue(TurnOnBindingProperty);
}
public static void SetTurnOnBinding(DependencyObject obj, bool value)
{
obj.SetValue(TurnOnBindingProperty, value);
}
// Using a DependencyProperty as the backing store for TurnOnBinding. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TurnOnBindingProperty =
DependencyProperty.RegisterAttached(
"TurnOnBinding",
typeof(bool),
typeof(PasswordHelper),
new UIPropertyMetadata(false, (d, e) =>
{
var pb = d as PasswordBox;
SetPasswordValue(pb, pb.Password);
pb.PasswordChanged += (s, x) => SetPasswordValue(pb, pb.Password);
}));
public static string GetPasswordValue(DependencyObject obj)
{
return (string)obj.GetValue(PasswordValueProperty);
}
public static void SetPasswordValue(DependencyObject obj, string value)
{
obj.SetValue(PasswordValueProperty, value);
}
// Using a DependencyProperty as the backing store for PasswordValue. This enables animation, styling, binding, etc...
public static readonly DependencyProperty PasswordValueProperty =
DependencyProperty.RegisterAttached(
"PasswordValue",
typeof(string),
typeof(PasswordHelper), new UIPropertyMetadata(null, (d, e) =>
{
PasswordBox p = d as PasswordBox;
string s = e.NewValue as string;
if (p.Password != s) p.Password = s;
}));
以及带有绑定的 XAML 部分:
<PasswordBox x:Name="passBox"
root:PasswordHelper.TurnOnBinding="True"
root:PasswordHelper.PasswordValue="{Binding Text,
ElementName=passSupport, Mode=TwoWay}"/>