Выделение / раскраска символов в wpf richtextbox - PullRequest
0 голосов
/ 15 ноября 2018
  public static void HighlightText(RichTextBox richTextBox,int startPoint,int endPoint, Color color)
    {
      //Trying to highlight charactars here
    }

Начальная точка - это первый символ, который должен быть выделен, а конечная точка - последний.

Некоторое время назад я искал в Интернете, но я до сих пор не понял, как решить свою проблему.проблема.Я надеюсь, что любой из вас знает, как решить эту проблему.

1 Ответ

0 голосов
/ 15 ноября 2018

Вот общая идея:

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));
}
...