本文介绍了在 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 中格式化单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!