Hello, I found a way how to color the text between tags in RichTextBox using C# WPF, but the problem is that it colors the text only once, no matter how many times the tag is found.
I'll post my code here, would anyone tell me what's wrong with it? Thanks!
In my Window_Loaded function:
TextRange textRange = new TextRange(lesson_content.Document.ContentStart, lesson_content.Document.ContentEnd);
string[] tags = new string[2];
tags[0] = "t";
tags[1] = "blue";
foreach (string tag in tags)
{
if (tag == "t")
{
string s = ExtractString(textRange.Text, tag);
Regex reg = new Regex(s, RegexOptions.Compiled | RegexOptions.IgnoreCase);
TextPointer start = lesson_content.Document.ContentStart;
while (start != null && start.CompareTo(lesson_content.Document.ContentEnd) < 0)
{
if start.GetPointerContext(LogicalDirection.Forward)==TextPointerContext.Text)
{
var match = reg.Match(start.GetTextInRun(LogicalDirection.Forward));
var textrange = new TextRange(start.GetPositionAtOffset(match.Index, LogicalDirection.Forward), start.GetPositionAtOffset(match.Index + match.Length, LogicalDirection.Backward));
textrange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Blue));
}
start = start.GetNextContextPosition(LogicalDirection.Forward);
}
}
ExtractString Function:
string ExtractString(string s, string tag)
{
string startTag = "<" + tag + ">";
int startIndex = s.IndexOf(startTag) + startTag.Length;
int endIndex = s.IndexOf(", startIndex);
return s.Substring(startIndex, endIndex - startIndex);
}
I tried to put two <t> tags, but it only colors the text between the first ones.