User.PasswordプロパティをPasswordBox(TwoWay)にバインドしたいと思います。PasswordBox.Passwordはバインド可能ではないため、これを修正するためにAttachedPropertiesを作成しました(1つはバインドをアクティブ化し、もう1つは実際のパスワードを保持します)。問題は、それらがバインドされないことです(GetBindingExpressionはnullを返します)。
また:
- AttachedPropertiesは機能します。PasswordBoxに入力すると、PasswordとPasswordValue(添付のprop)は正しく設定されますが、User.Passwordは空のままです。
- AttachedPropertyのバインドも機能しますが、その逆です。PasswordValueをTextBlockにバインドすると(TextBlock.Textがターゲット、helper: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}"/>