在 RichTextBox 中格式化单词

Format words in RichTextBox(在 RichTextBox 中格式化单词)
本文介绍了在 RichTextBox 中格式化单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

废话废话 @username废话废话 @anotherusername

推荐答案

这可能需要一些优化,因为我做得很快,但这应该可以帮助你开始

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

这篇关于在 RichTextBox 中格式化单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)