WPF RichTextBox中的突出显示/着色字符

时间:2018-11-15 12:52:28

标签: c# wpf richtextbox

  public static void HighlightText(RichTextBox richTextBox,int startPoint,int endPoint, Color color)
    {
      //Trying to highlight charactars here
    }

起点是应该突出显示的第一个字符,终点是最后一个突出显示的字符。

一段时间以来,我一直在网上寻找安静的地方,但是我仍然不知道如何解决我的问题。 我希望你们中的任何一个都知道如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

这是一般想法:

public static void HighlightText(RichTextBox richTextBox, int startPoint, int endPoint, Color color)
{
    //Trying to highlight charactars here
    TextPointer pointer = richTextBox.Document.ContentStart;
    TextRange range = new TextRange(pointer.GetPositionAtOffset(startPoint), pointer.GetPositionAtOffset(endPoint));
    range.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(color));
}

但是,由于偏移索引号与字符数不匹配,您将需要遍历文档以获得正确的文本位置。有些字符可能代表多个偏移位置。

这是执行此操作的方法。我不知道一种不循环浏览整个文档的方法。

public static void HighlightText(RichTextBox richTextBox, int startPoint, int endPoint, Color color)
{
    //Trying to highlight charactars here
    TextPointer pointer = richTextBox.Document.ContentStart;
    TextPointer start = null, end = null;
    int count = 0;
    while (pointer != null)
    {
        if (pointer.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
        {
            if (count == startPoint) start = pointer.GetInsertionPosition(LogicalDirection.Forward);
            if (count == endPoint) end = pointer.GetInsertionPosition(LogicalDirection.Forward);
            count++;
        }
        pointer = pointer.GetNextInsertionPosition(LogicalDirection.Forward);
    }
    if (start == null) start = richTextBox.Document.ContentEnd;
    if (end == null) end = richTextBox.Document.ContentEnd;

    TextRange range = new TextRange(start, end);
    range.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(color));
}
相关问题