이전 포스팅에서 Codebehind를 통해 MVVM을 유지하며 PasswordBox의 Password 속성을 Binding 하는 방법을 소개했었는데 Codebehind를 사용하지 않고 ViewModel에 Binding 하는 방법도 공유합니다. Attached Property를 사용합니다.
✅ PasswordBox DataBinding (Attached Property)
Attached Property를 사용해서 PasswordBox에 Password속성의 값에 접근할 수 있는 추가 속성을 부여하고 추가 속성에 ViewModel과 Binding 하여 ViewModel에서 사용할 수 있게 합니다.
PasswordExtends.cs (Attached Property)
public class PasswordExtends
{
#region IsPasswordBindable
public static bool GetIsPasswordBindable(DependencyObject obj)
{
return (bool)obj.GetValue(IsPasswordBindableProperty);
}
public static void SetIsPasswordBindable(DependencyObject obj, bool value)
{
obj.SetValue(IsPasswordBindableProperty, value);
}
public static readonly DependencyProperty IsPasswordBindableProperty =
DependencyProperty.RegisterAttached("IsPasswordBindable", typeof(bool), typeof(PasswordExtends), new PropertyMetadata(false, IsPasswordBindableChanged));
private static void IsPasswordBindableChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is PasswordBox passwordBox)) return;
if ((bool)e.NewValue)
{
passwordBox.PasswordChanged += PasswordBox_PasswordChanged;
}
else
{
passwordBox.PasswordChanged -= PasswordBox_PasswordChanged;
}
}
#endregion
#region BindablePassword
public static string GetBindablePassword(DependencyObject obj)
{
return (string)obj.GetValue(BindablePasswordProperty);
}
public static void SetBindablePassword(DependencyObject obj, string value)
{
obj.SetValue(BindablePasswordProperty, value);
}
public static readonly DependencyProperty BindablePasswordProperty =
DependencyProperty.RegisterAttached("BindablePassword", typeof(string), typeof(PasswordExtends), new PropertyMetadata(string.Empty));
private static void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
{
var passwordBox = (PasswordBox)sender;
SetBindablePassword(passwordBox, passwordBox.Password);
}
#endregion
}
IsPasswordBindable 추가 속성이 True 일 때, PasswordBox_PasswordChanged 가 동작하여 BindablePassword 속성이 Password 값을 갖도록 하는 로직입니다.
MainViewModel.cs
public class MainViewModel : BaseViewModel
{
private string _password;
public string PasswordString
{
get => _password;
set
{
_password = value;
this.OnPropertyChanged(nameof(PasswordString));
}
}
}
xaml
<StackPanel>
<PasswordBox Width="200" Height="30" local:PasswordExtends.IsPasswordBindable="True" local:PasswordExtends.BindablePassword="{Binding PasswordString, Mode=TwoWay}"/>
<TextBlock Width="200" Height="30" TextWrapping="Wrap" Text="{Binding PasswordString}"/>
</StackPanel>
PasswordBox에 값을 입력 시 TextBlock의 Text에 입력한 Password 가 나타납니다.
소스코드 첨부
✅ PasswordBox DataBinding (Attached Property) - 끝
관련 포스팅