开发者

How can I select multiple text segments in a WPF textbox?

Is it possible to select multiple parts of text within a WPF textbox? For instance, for a text开发者_运维问答box 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:

  • 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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜