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
SelectionFont = new Font(textBox. Font, FontStyle. Bold);
To change the appearance of characters Set the SelectionFont property to an appropriate font. To enable users to set the font family, size, and typeface in an application, you would typically use the FontDialog component.
Right-click the rich text box for which you want to enable or disable full rich-text formatting, and then click Rich Text Box Properties on the shortcut menu. Click the Display tab. To enable full rich-text formatting for the selected rich text box, select the Full rich text (images, tables, etc.)
Text can be assigned directly to the control, or can be loaded from a rich text format (RTF) or plain text file.
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;
}
I don't know your exact requirements, but I encourage you not to use a RichtextBox for Syntax-Highlighting purposes. There is an excellent component called AvalonEdit that can easily used for this. You can read more about AvalonEdit in this article: http://www.codeproject.com/Articles/42490/Using-AvalonEdit-WPF-Text-Editor
Syntaxdefinition for your requirement:
<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>
The complete demo-project can be downloaded here: http://oberaffig.ch/stackoverflow/avalonEdit.zip
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With