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

但是,我想使用代码来查找每个单词而不是以“@”开头的行,因此我可以格式化一个段落,例如:

等等等等@username等等等等等等@anotherusername

4

2 回答 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;
}
于 2013-08-07T01:11:17.693 回答
1

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>

enter image description here

The complete demo-project can be downloaded here: http://oberaffig.ch/stackoverflow/avalonEdit.zip

于 2013-08-13T12:11:13.843 回答