我想将User.Password属性绑定到PasswordBox(双向)。由于PasswordBox.Password不可绑定,因此我创建了一个附加属性来解决这个问题(一个用于激活绑定,一个用于保存实际密码)。但是它们无法绑定(GetBindingExpression返回null)。
另外:
- 附加属性是有效的。如果我在PasswordBox中输入,则Password和PasswordValue(附加属性)会正确设置,但是User.Password仍为空。 - 绑定附加属性也有效,但只能反过来使用:如果我将PasswordValue绑定到TextBlock(TextBlock.Text是目标,helper:PasswordValue是源),则它可以工作。但我不能使用这种方法,因为User的属性不是依赖对象。 - User.Password是可绑定的(User实现了INotifyPropertyChanged),我设法将User.Username绑定到TextBox.Text,其中Username和Password是类似的字符串属性。
以下是附加属性:
另外:
- 附加属性是有效的。如果我在PasswordBox中输入,则Password和PasswordValue(附加属性)会正确设置,但是User.Password仍为空。 - 绑定附加属性也有效,但只能反过来使用:如果我将PasswordValue绑定到TextBlock(TextBlock.Text是目标,helper:PasswordValue是源),则它可以工作。但我不能使用这种方法,因为User的属性不是依赖对象。 - User.Password是可绑定的(User实现了INotifyPropertyChanged),我设法将User.Username绑定到TextBox.Text,其中Username和Password是类似的字符串属性。
以下是附加属性:
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}"/>