This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Base Classes - TextBoxBase - Selection

The fifty-eighth part of the Windows Presentation Foundation Fundamentals tutorial looks at more members of the TextBoxBase class, which is inherited by some text input controls. This article looks at text selection members.


Over the past few articles we have looked at the text input controls of WPF and some of the methods, properties and events of the TextBoxBase class, which is inherited by the TextBox and RichTextBox controls. We've considered TextBoxBase functionality relating to text editing, styling and scrolling of text boxes. In this short article we'll recap two members relating to text selection.

SelectAll Method

We've already seen the SelectAll method in the article describing selection for the TextBox control. When used with a TextBox, is causes all of the text to become highlighted. The SelectAll method is defined in TextBoxBase, so it is also present for the RichTextBox control, where it allows you to select the entire document programmatically.


SelectionChanged Event

The SelectionChanged event is also provided by TextBoxBase. This event is raised whenever the selected portion of the text in a TextBox or RichTextBox is changed, either programmatically or in response to a user's activity. The event arguments provided by the event are an instance of the RoutedEventArgs class. The properties of the object allow you to determine the original source of the event or mark it as handled so that no other controls react to it.

private void MyTextBox_SelectionChanged(object sender, RoutedEventArgs e)
    Debug.WriteLine("Selected " + MyTextBox.SelectedText);
    e.Handled = true;
25 April 2014