【发布时间】:2015-08-19 05:48:53
【问题描述】:
我尝试在富文本框中突出显示文本。 我使用了按钮单击事件。 这是我的代码。
结果..... 这是冒泡排序。
position 和 targetposition 是对的。
但是,突出显示的字符与位置不同。
后来,文字没有画出来。
// 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;
}
}
我无法解决这个问题。 帮帮我..拜托
【问题讨论】:
-
您使用不同的代码发布了 5 次问题。但在每种情况下,您提供的代码都不足以帮助您。你能分享你的项目或至少完整的窗口代码来重现你的场景吗?
标签: wpf richtextbox