Skip to content

Instantly share code, notes, and snippets.

@smailliwcs
Created September 22, 2020 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smailliwcs/2a1e0881c4e94d66c4a3d4f674a6070b to your computer and use it in GitHub Desktop.
Save smailliwcs/2a1e0881c4e94d66c4a3d4f674a6070b to your computer and use it in GitHub Desktop.
Selecting text on keyboard navigation in WPF
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
RegisterClassHandlers();
Window window/* = ... */;
window.Show();
}
private void RegisterClassHandlers()
{
EventManager.RegisterClassHandler(
typeof(TextBox),
UIElement.GotKeyboardFocusEvent,
new KeyboardFocusChangedEventHandler(TextBox_GotKeyboardFocus));
EventManager.RegisterClassHandler(
typeof(TextBox),
UIElement.LostFocusEvent,
new RoutedEventHandler(TextBox_LostFocus));
}
private void TextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
if (e.KeyboardDevice.IsKeyDown(Key.Tab))
{
((TextBox)sender).SelectAll();
}
}
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
((TextBox)sender).Select(0, 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment