[英]Format words in 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;
}
我不知道您的具體要求,但我建議您不要使用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>
完整的演示項目可以在這里下載: http : //oberaffig.ch/stackoverflow/avalonEdit.zip
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.