我想将User.Password属性绑定到PasswordBox(TwoWay).由于PasswordBox.Password不可绑定,我制作了AttachedProperties来修复此问题(一个用于激活绑定,另一个用于保存实际密码).问题是它们不会绑定(GetBindingExpression返回null).
也:
> AttachedProperties工作.如果我输入PasswordBox,则Password和PasswordValue(附加道具)设置正确,但User.Password保持为空.
>绑定AttachedProperty也可以,但只是相反:如果我将PasswordValue绑定到TextBlock(TextBlock.Text是目标,帮助者:PasswordValue是源)它可以工作.只有我不能使用它,因为User的属性不是依赖项对象.
> User.Password是可绑定的(用户实现INotifyPropertyChanged),我设法将User.Username绑定到TextBox.Text并且(用户名和密码是类似的字符串属性)
以下是AttachedProperties:
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}"/>
最佳答案 很抱歉,我不能说你的代码有什么问题(恕我直言它应该可以工作),但由于我在Silverlight中遇到类似的问题,并且设计师并不喜欢绑定到附加属性,我发现他们不值得麻烦.
我目前首选的扩展控件行为的方法是使用System.Windows.Interactivity.Behavior基类(请参阅
here和
here),然后将我的行为附加到控件.
因此,您需要一个类PasswordBehavior:Behavior< PasswordBox>,它会覆盖OnAttached(),并订阅passwordBox的PasswordChanged事件,并且具有一个名为PasswordValue的可绑定DependencyProperty.在事件处理程序中更改dp的值,并在dp的回调上更改控件的Password值.