Format words in RichTextBox

c#, formatting, richtextbox, wpf

Solution

This could probably use some optimization as I did it quick, but this should get you started

private void RichTextBox_TextChanged(object sender, TextChangedEventArgs e)
{    
     tweetText.TextChanged -= RichTextBox_TextChanged;
     int pos = tweetText.CaretPosition.GetOffsetToPosition(tweetText.Document.ContentEnd);

     foreach (Paragraph line in tweetText.Document.Blocks.ToList())
     {
        string text = new TextRange(line.ContentStart,line.ContentEnd).Text;

        line.Inlines.Clear();

        string[] wordSplit = text.Split(new char[] { ' ' });
        int count = 1;

        foreach (string word in wordSplit)
        {
            if (word.StartsWith("@"))
            {
                Run run = new Run(word);
                run.FontWeight = FontWeights.Bold;
                line.Inlines.Add(run);
            }
            else
            {
                line.Inlines.Add(word);
            }

            if (count++ != wordSplit.Length)
            {
                 line.Inlines.Add(" ");
            }
        }
     }

     tweetText.CaretPosition = tweetText.Document.ContentEnd.GetPositionAtOffset(-pos);
     tweetText.TextChanged += RichTextBox_TextChanged;
}

Problem

I am using the following code to find each line that starts with "@" and format it by making it bold: ``` foreach (var line in tweetText.Document.Blocks) { var text = new TextRange(line.ContentStart, line.ContentEnd).Text; line.FontWeight = text.StartsWith("@") ? FontWeights.Bold : FontWeights.Normal; } ``` However, I would like to use the code to find each word instead of line beginning with "@" so I could format a paragraph like: Blah blah blah @username blah blah blah blah @anotherusername

Original source