我正在尝试在WPF RichTextBox中实现以编程方式选择的(使用正则表达式)文本格式。用例只是一个WPF RichTextBox,用户在其中键入文本。但是,为了提高或加快可读性,我想在键入文本时合并一些自动格式设置。
How to select text from the RichTextBox and then color it?中的以下代码正是我想做的。但是,据我所知,此代码用于WinForms RichTextBox:
public void ColourRrbText(RichTextBox rtb)
{
Regex regExp = new Regex(@"\b(For|Next|If|Then)\b");
foreach (Match match in regExp.Matches(rtb.Text))
{
rtb.Select(match.Index, match.Length);
rtb.SelectionColor = Color.Blue;
}
}
我尝试将其转换如下:
public static void ColorSpecificText(RichTextBox rtb)
{
TextRange textRange = new TextRange(rtb.Document.ContentEnd, rtb.Document.ContentEnd);
Regex regex = new Regex(@"\b(For|Next|If|Then)\b");
foreach (Match match in regex.Matches(textRange.Text))
{
textRange.Select(match.Index, match.Length); // <--- DOESN'T WORK
textRange.SelectionColor = Color.Blue; // <--- DOESN'T WORK
}
}
但是,我一直坚持如何将“ match.Index,match.Length”和“ SelectionColor”语法转换为WPF RichTextBox知道如何处理的语法。我搜索了其他帖子,但大多数似乎也是针对WinForms RichTextBox,而不是WPF。任何指导将不胜感激。
这是语法:
TextRange textRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
textRange.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Black);
Regex regex = new Regex(@"\b(For|Next|If|Then)\b");
int i = 0;
foreach (Match match in regex.Matches(textRange.Text))
{
var startOffset = textRange.Start.GetPositionAtOffset(i + match.Index);
var endOffset = textRange.Start.GetPositionAtOffset(i + match.Index + match.Length);
new TextRange(startOffset, endOffset).ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.LightBlue);
i += 4; // could be something else
}
尽管由于您的策略可能无法正确突出显示。恐怕字符串索引不足以创建正确的TextPointer。 +4用于跳过格式设置开销,因此如果存在其他格式,它可能不起作用。