Ten*_*iko 5 data-binding wpf binding attached-properties
我想将 User.Password 属性绑定到 PasswordBox (TwoWay)。由于PasswordBox.Password 不可绑定,我制作了 AttachedProperties 来解决此问题(一个用于激活绑定,一个用于保存实际密码)。问题是它们不会绑定(GetBindingExpression 返回 null)。
还:
以下是附加属性:
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;
}));
Run Code Online (Sandbox Code Playgroud)
以及带有绑定的 XAML 部分:
<PasswordBox x:Name="passBox"
root:PasswordHelper.TurnOnBinding="True"
root:PasswordHelper.PasswordValue="{Binding Text,
ElementName=passSupport, Mode=TwoWay}"/>
Run Code Online (Sandbox Code Playgroud)
抱歉,我不能说你的代码出了什么问题(恕我直言,它应该可以工作),但由于我在 Silverlight 中遇到了类似的问题,并且设计者并不真正喜欢绑定到附加属性或从附加属性绑定,所以我发现他们不值得这么麻烦。
我当前扩展控件行为的首选方法是使用 System.Windows.Interactivity.Behavior 基类(请参阅此处和此处),然后将我的行为附加到控件。
因此,您需要一个class PasswordBehavior : Behavior<PasswordBox>,它覆盖OnAttached(),并订阅passwordBox 的PasswordChanged 事件,并且有一个名为PasswordValue 的可绑定DependencyProperty。在事件处理程序中更改 dp 的值,并在 dp 的回调中更改控件的密码值。
| 归档时间: |
|
| 查看次数: |
7208 次 |
| 最近记录: |