I'm tried highlighting text in richtextbox. I used button click event. this my code.
Result..... This is a bubble sort.
position and targetposition is right.
However, the highlighted character is different from the position.
Later, the text is not painted.
// print one line
this.rtb1.AppendText(this.IntToString(traceInfo.SortingNumbers));
this.rtb1.AppendText("\r\n");
ChangeTextColor(traceInfo.Position, traceInfo.TargetPosition);
private void ChangeTextColor(int position, int targetPosition)
{
int length;
int pos = GetTextPositionAndLength(position, count, out length);
TextRange textRange = new TextRange(rtb1.Document.ContentStart, rtb1.Document.ContentEnd);
TextPointer startPointer = textRange.Start.GetPositionAtOffset(pos);
TextPointer endPointer = textRange.Start.GetPositionAtOffset(pos + length);
TextRange tr2 = new TextRange(startPointer, endPointer);
tr2.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Red));
int pos2 = GetTextPositionAndLength(targetPosition, count, out length);
TextRange textRange2 = new TextRange(rtb1.Document.ContentStart, rtb1.Document.ContentEnd);
TextPointer startPointer2 = textRange2.Start.GetPositionAtOffset(pos2);
TextPointer endPointer2 = textRange2.Start.GetPositionAtOffset(pos2 + length);
TextRange tr4 = new TextRange(startPointer2, endPointer2);
tr4.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.LightBlue));
}
private int GetTextPositionAndLength(int position, int lineIndex, out int length)
{
// First charcter position index of lineIndex
int richtTextLineIndex = GetFirstCharIndexFromLine(lineIndex);
if (position == 0)
{
length = GetTextLength(0, lineIndex);
return richtTextLineIndex;
}
int index = 0;
int posIter = 0;
string line = Line(lineIndex);
length = 0;
for (index = 0; index < line.Length; index++)
{
if (line[index] == ' ')
{
posIter++;
if (posIter == position)
{
index++;
length = GetTextLength(index, lineIndex);
break;
}
}
}
return index + richtTextLineIndex;
}
}
I can't solve this problem. Help me ..please

