This seems to work well for me. It's basically a recap of some earlier posts. I just put this into my MainWindow.xaml.cs file in the constructor. I create two handlers, one for keyboard, and one for the mouse, and funnel both events into the same function, HandleGotFocusEvent
, which is defined right after the constructor in the same file.
public MainWindow()
{
InitializeComponent();
EventManager.RegisterClassHandler(typeof(TextBox),
UIElement.GotKeyboardFocusEvent,
new RoutedEventHandler(HandleGotFocusEvent), true);
EventManager.RegisterClassHandler(typeof(TextBox),
UIElement.GotMouseCaptureEvent,
new RoutedEventHandler(HandleGotFocusEvent), true);
}
private void HandleGotFocusEvent(object sender, RoutedEventArgs e)
{
if (sender is TextBox)
(sender as TextBox).SelectAll();
}