我可以在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()方法确定的绝对字符位置。