我试图在我的 RichTextBox 中突出显示一行。我的尝试是获取该行在文本中的位置,然后创建一个表示 text.Substring(offset, word.Length)
的 TextRange。但不知何故,RichTextBox 仅突出显示前一行的最后 2 个字符和实际行的某些字符或实际行的一部分。我目前的方法是这个:
public void SelectLine(string text)
{
int i = new TextRange(editor.Document.ContentStart, editor.Document.ContentEnd).Text.IndexOf(text);
TextPointer start = editor.Document.ContentStart.GetPositionAtOffset(i);
TextPointer end = start.GetPositionAtOffset(text.Length);
TextRange r = new TextRange(start, end);
if (r != null)
{
r.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Red);
r.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.White);
}
}
这就是我尝试选择第二行时的样子:
你知道为什么会这样吗?
编辑: 我当前的方法包括一个 WPF RichTextBox。
最佳答案
经过大量搜索,我终于找到了这个解决方案。我在计数到给定行的同时遍历文档的 block 。 我不在乎,是整个段落还是只突出显示行,因为我写了一个小代码编辑器,它应该显示错误并在给定的源代码中突出显示它。这是我的突出显示代码:
public void SelectLine(int line)
{
int c = 0;
TextRange r;
foreach (var item in editor.Document.Blocks)
{
if (line == c)
{
r = new TextRange(item.ContentStart, item.ContentEnd);
if (r.Text.Trim().Equals(""))
{
continue;
}
r.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Red);
r.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.White);
return;
}
c++;
}
}
它遍历文档的 block 并检查给定的 block 是否为空。如果是这样,那么将研究下一个 block 。
关于c# - 突出显示 RichTextBox 中的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21952809/