Reputation: 37524
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.
Upvotes: 9
Views: 4851
Reputation: 62929
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".CollectionChanged
handler to "AdditionalRanges" that uses TextRange.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:
TextChanged
handler to know when to update the "Text" property, and a PropertyChangedCallback to know when to update the FlowDocumentUpvotes: 15
Reputation: 1862
the standard WPF TextBox does not support such behaviour, unfortunately. So the only way I see to get that functionality would be implementing your own text box control (maybe based on the standard text box ControlTemplate).
Cheers, Alex
Upvotes: 2