How can you add "Select All" behaviour for all TextBox in your WPF application?
Here's how you can add Select All behaviour for all TextBox in your WPF application.
-
Published by Kunal Chowdhury
Lets say, you have a single Window with 100 TextBoxs in it. In this case though you can write the event definition inside a single implementation but you have to register the event for 100 times. Now imagine the same behaviour for 10 Windows inside the same application. Here you have to write the event implementation for each and every Window & register the event for each TextBox. This will definately clutter your code.
protected override void OnStartup(StartupEventArgs e)
{
EventManager.RegisterClassHandler(typeof(TextBox), TextBox.GotFocusEvent, new RoutedEventHandler(TextBox_GotFocus));
base.OnStartup(e);
}
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
TextBox tb = sender as TextBox;
tb.Focus();
tb.SelectAll();
}
Solution Architect & Former Microsoft MVP
Kunal Chowdhury is an enterprise solution architect and former multi-year Microsoft MVP. He is the author of three technical books: Windows Presentation Foundation Development Cookbook, Mastering Visual Studio 2017, and the Mastering Visual Studio 2019.
He publishes technical articles on Kunal-Chowdhury.com.