更改 WPF C# 中某些部分文本的颜色和字体 [英] Change color and font for some part of text in WPF C#

查看:66
本文介绍了更改 WPF C# 中某些部分文本的颜色和字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法更改我想放在 TextBox 或 RichTextBox 上的某些文本部分的颜色和字体.我正在使用 C# WPF.

Is there a way to change color and font for some part of text which I want to put on TextBox or RichTextBox. I am using C# WPF.

例如

 richTextBox.AppendText("Text1 " + word + " Text2 ");

变量词例如是来自 Text1 和 Text2 的其他颜色和字体.是否有可能以及如何做到这一点?

Variable word for example to be other color and font from Text1 and Text2. Is it possible and how to do this?

推荐答案

如果您只想进行一些快速着色,最简单的解决方案可能是将 RTB 内容的末尾用作范围并对其应用格式.例如:

If you just want to do some quick coloring, the simplest solution may be to use the end of the RTB content as a Range and apply formatting to it. For example:

TextRange rangeOfText1 = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);
rangeOfText1.Text = "Text1 ";
rangeOfText1.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
rangeOfText1.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);

TextRange rangeOfWord = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);
rangeOfWord.Text = "word ";
rangeOfWord.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
rangeOfWord.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Regular);

TextRange rangeOfText2 = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);
rangeOfText2.Text = "Text2 ";
rangeOfText2.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
rangeOfText2.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);

如果您正在寻找更高级的解决方案,我建议您阅读 有关流文档的 Microsoft Doc,因为它为您设置文本格式提供了极大的灵活性.

If you are looking for a more advanced solution, I suggest reading this Microsoft Doc about Flow Document, as it gives you a great flexibility in formatting your text.

这篇关于更改 WPF C# 中某些部分文本的颜色和字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆