I have a wpf application and I am following the mvvm pattern carefully for reasons beyond my control. I do not want to databind to my PasswordBox for security reasons beyond
You can create your attached DependencyProperty
and use it as a XAML or in code. Example:
Listing of PasswordBehaviors
:
public static class PasswordBehaviors
{
public static void SetIsClear(DependencyObject target, bool value)
{
target.SetValue(IsClearProperty, value);
}
public static readonly DependencyProperty IsClearProperty =
DependencyProperty.RegisterAttached("IsClear",
typeof(bool),
typeof(PasswordBehaviors),
new UIPropertyMetadata(false, OnIsClear));
private static void OnIsClear(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue is bool && ((bool)e.NewValue) == true)
{
PasswordBox MyPasswordBox = sender as PasswordBox;
if (MyPasswordBox != null)
{
MyPasswordBox.Clear();
}
}
}
}
Using with EventTrigger
:
True
Using with DataTrigger
(in Style
/DataTemplate
/etc
):
Using with Trigger
(in Style
):
Using behind code:
private void Clear_Click(object sender, RoutedEventArgs e)
{
PasswordBehaviors.SetIsClear(MyPasswordBox, true);
}
Copmlete example:
XAML
True
False
Code behind
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
//private void Clear_Click(object sender, RoutedEventArgs e)
//{
// PasswordBehaviors.SetIsClear(MyPasswordBox, true);
//}
//private void ResetClear_Click(object sender, RoutedEventArgs e)
//{
// PasswordBehaviors.SetIsClear(MyPasswordBox, false);
//}
}
public static class PasswordBehaviors
{
public static void SetIsClear(DependencyObject target, bool value)
{
target.SetValue(IsClearProperty, value);
}
public static readonly DependencyProperty IsClearProperty =
DependencyProperty.RegisterAttached("IsClear",
typeof(bool),
typeof(PasswordBehaviors),
new UIPropertyMetadata(false, OnIsClear));
private static void OnIsClear(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue is bool && ((bool)e.NewValue) == true)
{
PasswordBox MyPasswordBox = sender as PasswordBox;
if (MyPasswordBox != null)
{
MyPasswordBox.Clear();
}
}
}
}