views:

238

answers:

2

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.

+2  A: 

Hi there,

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

alexander.biskop
+9  A: 

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:

  • Create a class deriving from RichTextBox
  • Add an "AdditionalRanges" property of type ObservableCollection<TextRange> which will contain all selected ranges except the current TextSelection
  • Override OnPreviewMouseLeftButtonDown: If Ctrl is pressed, combine the current TextSelection into your "AdditionalRanges" property and clear Selection, otherwise clear "AdditionalRanges".
  • In the constructor, add a 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:

  • An "AllRanges" property that combines the TextSelection with AdditionalRanges
  • A bindable "Text" property
  • A bindable "SelectedText" property

These are all quite trivial to implement.

Final notes:

  • When updating AdditionalRanges or computing AllRanges, if the TextSelection overlaps an existing AdditionalRange, replace it with a combined range otherwise add the TextSelection to the list.
  • You can add a TextChanged handler to know when to update the "Text" property, and a PropertyChangedCallback to know when to update the FlowDocument
Ray Burns