Created
September 22, 2020 15:26
-
-
Save smailliwcs/2a1e0881c4e94d66c4a3d4f674a6070b to your computer and use it in GitHub Desktop.
Selecting text on keyboard navigation in WPF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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