Format words in RichTextBox

I use the following code to find every line starting with "@" and format it to make 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 the line starting with "@", so I could format the paragraph as follows:

Blah blah blah @username blah blah blah blah @anotherusername

+6
source share
2 answers

This can probably use some optimization as I did it quickly, but it should help you get 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; } 
+7
source

I do not know your exact requirements, but I recommend that you do not use RichtextBox for syntax purposes. There is a great AvalonEdit component that can be easily used for this. You can read more about AvalonEdit in this article: http://www.codeproject.com/Articles/42490/Using-AvalonEdit-WPF-Text-Editor

The syntax definition for your requirement is:

 <SyntaxDefinition name="customSyntax" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008"> <Color name="User" foreground="Blue" fontWeight="bold" /> <RuleSet> <Span color="User" begin="@" end =" "/> </RuleSet> </SyntaxDefinition> 

enter image description here

The full demo project can be downloaded here: http://oberaffig.ch/stackoverflow/avalonEdit.zip

+1
source

Source: https://habr.com/ru/post/1495639/


All Articles