问题
I am trying to implement programmatically selected (using regex) text formatting in a WPF RichTextBox. The use case is simply a WPF RichTextBox in which the user types text. However, to improve or accelerate readability i want to incorporate some automatic formatting as the text is typed.
The following code from How to select text from the RichTextBox and then color it? is exactly what i am trying to do. However, as far as i can tell this code is for a 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;
}
}
I have tried to convert it as follows:
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
}
}
However, i am stuck on how to convert the "match.Index, match.Length" and the "SelectionColor" syntax to something that the WPF RichTextBox knows how to handle. I have searched other posts, but most also seem to be for WinForms RichTextBox, not WPF. Any guidance would be greatly appreciated.
回答1:
This is the syntax:
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 wordStartOffset = textRange.Start.GetPositionAtOffset(i + match.Index);
var wordEndOffset = textRange.Start.GetPositionAtOffset(i + match.Index + match.Length);
var wordRange = new TextRange(wordStartOffset, wordEndOffset);
wordRange.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.LightBlue);
i += 4; // could be something else
}
Although it may not highlight correctly because of your strategy. I'm afraid string index is not enough to create the proper TextPointer. +4 is used to skip formatting overheads, that's why it may not work if other formattings are present.
来源:https://stackoverflow.com/questions/61251128/selected-text-formatting-in-wpf-richtexbox