c# - 在 RichTextBox 中格式化单词

我正在使用以下代码查找以“@”开头的每一行并将其设置为粗体:

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/

相关文章:

sql - 计算组百分比到小数点后 2 位 - SQL

vba - 删除图表系列但保留其格式

excel - 我的 Excel 行被锁定在 409.5 的高度,我想增加大小

jsp - IntelliJ JSP 格式化

excel - 如何将 Excel 2010 中的条件格式复制到基于其他单元格内容的其他单元格?

python - 使用 Python 格式化 Excel 中的单元格

python - 条件格式 xlwt

ruby - 在 ERB 模板中转义换行符/行尾

kotlin - 如何将粗体、斜体、下划线等格式添加到 Kotlin 文档 (KDoc)

objective-c - 你如何调整 Xcode 的 Objective C 参数的自动缩进?