我正在使用以下代码查找以“@”开头的每一行并将其设置为粗体:
foreach (var line in tweetText.Document.Blocks)
{
var text = new TextRange(line.ContentStart,
line.ContentEnd).Text;
line.FontWeight = text.StartsWith("@") ?
FontWeights.Bold : FontWeights.Normal;
}
但是,我想使用代码来查找每个单词而不是以“@”开头的行,因此我可以格式化如下段落:
Blah blah blah @username blah blah blah blah @anotherusername
最佳答案
这可能需要一些优化,因为我做得很快,但这应该可以帮助您开始
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;
}
https://stackoverflow.com/questions/18092639/