在RichTextBox中格式化文字

6

我正在使用以下代码查找以“@”开头的每一行,并通过使其加粗来格式化:

foreach (var line in tweetText.Document.Blocks)
        {
            var text = new TextRange(line.ContentStart,
                           line.ContentEnd).Text;
            line.FontWeight = text.StartsWith("@") ?
                           FontWeights.Bold : FontWeights.Normal;
        }

然而,我希望使用代码来查找每个单词,而不是以“@”开头的行,这样我就可以像下面这样格式化段落:

胡言乱语@用户名胡言乱语胡言乱语@另一个用户名

2个回答

7

这段代码可能需要进行一些优化,因为我写得比较快,但是它可以帮助你入门。

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;
}

这在TextRange部分引发了未处理的异常。请注意,这是在richtextbox_textchanged事件中使用,并且是使用WPF编写的。 - Rhys Towey
RichTextBox不支持“.Document.Blocks.ToList()”。 - Rhys Towey
它继承自 TextElementCollection ,该类又是 IEnumerable<T> 的继承者。您确定您正在使用 System.Windows.Controls.RichTextBox 而不是 System.Windows.Forms.RichTextBox 在 WPF 中吗? - jamesSampica
ToList 是 LINQ 的扩展方法。请确保你有 using System.Linq; - Abe Heidebrecht
谢谢Abe。然而,当你运行代码时,文本会混在一起(忽略空格),并且文本光标始终位于文本开头。有什么想法吗? - Rhys Towey
显示剩余4条评论

1
我不知道您的具体要求,但我建议您不要使用RichtextBox来进行语法高亮。有一个名为AvalonEdit的优秀组件可以轻松地用于此目的。您可以在这篇文章中了解更多关于AvalonEdit的信息:http://www.codeproject.com/Articles/42490/Using-AvalonEdit-WPF-Text-Editor 您的要求的语法定义:
<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

完整的演示项目可以在此处下载:http://oberaffig.ch/stackoverflow/avalonEdit.zip

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接