如何在 WPF 文本框中选择多个文本段?
是否可以在 WPF 文本框中选择文本的多个部分?例如,对于包含字符串 THIS IS A TEST
的文本框,我希望能够突出显示 THIS
,然后按住 Ctrl 并突出显示 TEST
> 无需取消选择THIS
。
有关我的目标的视觉线索,请参阅 这篇文章介绍了 Firefox 中的功能。
如果默认情况下无法实现此目的,我想知道 WPF 中是否有任何第三方控件可以实现此目的。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
WPF 的 TextBox 和 RichTextBox 类不直接支持多重选择,但与 WPF 的大多数部分一样,可以非常轻松地自定义现有的 RichTextBox 以获得此功能。
步骤如下:
ObservableCollection
类型的“AdditionalRanges”属性,该属性将包含除当前 TextSelection 之外的所有选定范围OnPreviewMouseLeftButtonDown
: 如果按下 Ctrl 键,将当前的 TextSelection 合并到“AdditionalRanges”属性中并清除 Selection,否则清除“AdditionalRanges”。CollectionChanged
处理程序,该处理程序使用TextRange.ApplyPropertyValue()
使集合中添加的范围突出显示,而删除的范围正常显示。在您的实现中,为了方便起见,我还建议您实现更多属性: 将
这些实现起来都很简单。
最后注意事项:
TextChanged
处理程序来了解何时更新“Text”属性,并添加一个 PropertyChangedCallback 来了解何时更新 FlowDocumentWPF'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 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:
TextChanged
handler to know when to update the "Text" property, and a PropertyChangedCallback to know when to update the FlowDocument不幸的是,标准 WPF TextBox 不支持这种行为。
因此,我认为获得该功能的唯一方法是实现您自己的文本框控件(可能基于标准文本框 ControlTemplate)。
干杯,亚历克斯
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