Hi: I am trying to implement programmatically selected text formatting in a WPF RichTextBox.
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;
}
}
However, i am stuck on how to fully convert the above code to code that WPF RichTextBox knows how to handle. The following code from wpf richtextbox selection with regex provides some very helpful guidance. So this is where i am:
public static void ColorSpecificText(RichTextBox richTextBox)
{
var newRun = new Run(); // <-- I THINK I NEED TO RELATE THIS CODE TO MY textRange OR TO MY richTextBox, BUT NOT SURE / DON'T KNOW HOW TO DO IT
TextRange textRange = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);
Regex regex = new Regex(@"\b(For|Next|If|Then)\b");
foreach (Match match in regex.Matches(textRange.Text))
{
TextPointer start = newRun.ContentStart.GetPositionAtOffset(match.Index, LogicalDirection.Forward);
TextPointer end = newRun.ContentStart.GetPositionAtOffset(match.Index + match.Length, LogicalDirection.Backward);
if (start != null && end != null)
{
richTextBox.Selection.Select(start, end);
richTextBox.Selection.ApplyPropertyValue(Run.BackgroundProperty, "Red");
}
}
}
For example, when applying this code to a WPF RichTextBox with the string "Next Hello World", the above code doesn't generate any errors, but doesn't work either ("Next" doesn't get highlighted). I don't have reason to believe that the regex would be the issue as i tested it at regex101.com. My guess is i am missing something in declaring newRun and how to relate it either to textRange or richTextBox. Thanks for any guidance on how to resolve this.