Is it possible to select multiple parts of text within a WPF textbox? For instance, for a textbox that contains the string THIS IS A TEST, I want to be able to highlight THIS, then hold Ctrl and highlight TEST without unselecting THIS.
For a visual clue about what I’m aiming at, see this article about the feature in Firefox.
If by default there is no way to accomplish this, I would like to know if there is any third-party control implemented in WPF that does.
WPF’s TextBox and RichTextBox classes do not directly support multiselection, but as with most parts of WPF it’s extremely easy to customize its existing RichTextBox to get this ability.
The steps are:
ObservableCollection<TextRange>which will contain all selected ranges except the current TextSelectionOnPreviewMouseLeftButtonDown: If Ctrl is pressed, combine the current TextSelection into your “AdditionalRanges” property and clear Selection, otherwise clear “AdditionalRanges”.CollectionChangedhandler to “AdditionalRanges” that usesTextRange.ApplyPropertyValue()to make added ranges in the collection appear hilighted and removed ranges appear normally.In your implementation I also recommend you implement a few more properties for convenience:
These are all quite trivial to implement.
Final notes:
TextChangedhandler to know when to update the “Text” property, and a PropertyChangedCallback to know when to update the FlowDocument