c# - 如何将所选文本的开始和结束索引转换为精确的 TextRange?
问题描述
我可以在 RichTextBox 中获取所选文本的确切开始和结束索引,但是如何反过来呢?使用实际的开始和结束索引(字符位置)再次选择文本作为范围以对其执行一些格式化 - 比如突出显示背景。
示例 - 使用鼠标选择文本和应用的突出显示不重叠
private void textBox_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if(this.textBox.Selection.Text.Length > 0)
highlightFromSelection(this.textBox, new SolidColorBrush(Colors.Yellow));
}
public void highlightFromSelection(RichTextBox textBox, SolidColorBrush color)
{
TextPointer docStart = textBox.Document.ContentStart;
TextPointer selectionStart = textBox.Selection.Start;
TextPointer selectionEnd = textBox.Selection.End;
TextRange start = new TextRange(docStart, selectionStart);
TextRange end = new TextRange(docStart, selectionEnd);
int indexStart = start.Text.Length;
int indexEnd = end.Text.Length;
MessageBox.Show("start: " + indexStart + " end: " + indexEnd);
ApplyHighlight(textBox, indexStart, indexEnd, color);
}
public void ApplyHighlight(RichTextBox textBox, int startIndex, int endIndex, SolidColorBrush color)
{
TextPointer docStart = textBox.Document.ContentStart;
//This code highlights the wrong part of text - its the closest I could get
//i.e. the highlighting does not overlap exactly with the original selection made
//TextPointer startPointer = docStart.GetPositionAtOffset(startIndex, LogicalDirection.Forward);
//TextPointer endPointer = docStart.GetPositionAtOffset(endIndex, LogicalDirection.Backward);
//TextRange range = new TextRange(startPointer, endPointer);
//range.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Yellow));
}
编辑: 我只能使用由 highlightFromSelection() 方法确定的绝对字符位置。
解决方案
推荐阅读
- hp-uft - 如何使用 HP UFT 循环浏览 webtable 并打印第 1 列和第 2 列中每一行的文本
- haskell - 如何修改类型声明,这样我们就不必将 Either 更改为类型构造函数?
- linux - Ansible:“msg”:“基本:服务器返回的 HTTP 响应错误。代码 503”
- mysql - SQL,表连接不会显示正确的输出
- angular - 跳过 FormControl 的 valueChanges 中程序所做的更改
- c# - 如何使用数据集在 Visual Basic/C# 中读取和写入相同的 XML 文件?
- r - R Simmer 中的即时库存补货
- sql - 将表链接到自身并获取关系 ID
- python - Dockerfile : 安装包以运行 python3 脚本
- kubernetes - Kubernetes 领导者选举 - HTTP 服务器响应错误