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
Has been working as a C# developer on contract for the last several years, including 3 years at Microsoft. Previously worked with Visual Basic and Microsoft Access VBA, and have developed code for Word, Excel and Outlook. Started working with WPF in 2007 when part of the Microsoft WPF team. For the last eight years has been working primarily as a senior WPF/C# and Silverlight/C# developer. Currently working as WPF developer with BioNano Genomics in San Diego, CA redesigning their UI for their camera system. he can be reached at qck1@hotmail.com.