Change color and font for some part of text in WPF C#(在 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 内容的结尾作为 Range 并对其应用格式.例如:
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 about Flow Document,因为它为您提供了极大的灵活性来格式化您的文本.
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# 中更改部分文本的颜色和字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 WPF C# 中更改部分文本的颜色和字体
基础教程推荐
- C# 从 List<List<int>> 中删除重 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
