Introduction
I had a situation with a couple of PasswordBox
controls, and it was frustrating because you almost never want to add to a password, especially since the actual text is obscured. I looked around for a solution. There were some custom TextBox
controls to do this, but I really like to use a behavior when the impact is so minor on a control. I also found some interaction behaviors but I do not like to use these unless I have to, and I did find a behavior that only worked on TextBox
controls. I therefore made my own behavior.
The Code
The following is the code for the behavior:
public class SelectAllFocusBehavior
{
public static bool GetEnable(FrameworkElement frameworkElement)
{
return (bool)frameworkElement.GetValue(EnableProperty);
}
public static void SetEnable(FrameworkElement frameworkElement, bool value)
{
frameworkElement.SetValue(EnableProperty, value);
}
public static readonly DependencyProperty EnableProperty =
DependencyProperty.RegisterAttached("Enable",
typeof(bool), typeof(SelectAllFocusBehavior),
new FrameworkPropertyMetadata(false, OnEnableChanged));
private static void OnEnableChanged
(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var frameworkElement = d as FrameworkElement;
if (frameworkElement == null) return;
if (e.NewValue is bool == false) return;
if ((bool)e.NewValue)
{
frameworkElement.GotFocus += SelectAll;
frameworkElement.PreviewMouseDown += IgnoreMouseButton;
}
else
{
frameworkElement.GotFocus -= SelectAll;
frameworkElement.PreviewMouseDown -= IgnoreMouseButton;
}
}
private static void SelectAll(object sender, RoutedEventArgs e)
{
var frameworkElement = e.OriginalSource as FrameworkElement;
if (frameworkElement is TextBox)
((TextBoxBase)frameworkElement).SelectAll();
else if (frameworkElement is PasswordBox)
((PasswordBox)frameworkElement).SelectAll();
}
private static void IgnoreMouseButton
(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
var frameworkElement = sender as FrameworkElement;
if (frameworkElement == null || frameworkElement.IsKeyboardFocusWithin) return;
e.Handled = true;
frameworkElement.Focus();
}
}
Using the Code
This is how this behavior would be used within WPF XAML:
<TextBox Width="150"
Margin="20"
local:SelectAllFocusBehavior.Enable="True"
Text="This is with Behavior" />
History
- 2018/06/20: Initial version