问题
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
回答1:
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;
}
回答2:
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
来源:https://stackoverflow.com/questions/18092639/format-words-in-richtextbox