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".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 FlowDocumentthe 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With