在 TextBlock 中格式化文本

编程入门 行业动态 更新时间:2024-10-26 03:25:45
本文介绍了在 TextBlock 中格式化文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何在我的 WPF 应用程序中对 TextBlock 控件内的文本进行格式化?

How do I achieve formatting of a text inside a TextBlock control in my WPF application?

例如:我希望某些单词以粗体显示,其他以斜体显示,有些以不同颜色显示,例如:

e.g.: I would like to have certain words in bold, others in italic, and some in different colors, like this example:

我的问题背后的原因是这个实际问题:

The reason behind my question is this actual problem:

lblcolorfrom.Content = "Colour From: " + colourChange.ElementAt(3).Value.ToUpper();

我希望字符串的第二部分为粗体,并且我知道我可以使用两个控件(标签、文本块等),但我宁愿不使用,因为已经有大量控件在使用.

I would like the second part of the string to be bold, and I know that I could use two controls (Labels, TextBlocks, etc.) but I'd rather not, due the vast amount of controls already in use.

推荐答案

您需要使用 内联:

You need to use Inlines:

<TextBlock.Inlines> <Run FontWeight="Bold" FontSize="14" Text="This is WPF TextBlock Example. " /> <Run FontStyle="Italic" Foreground="Red" Text="This is red text. " /> </TextBlock.Inlines>

有绑定:

<TextBlock.Inlines> <Run FontWeight="Bold" FontSize="14" Text="{Binding BoldText}" /> <Run FontStyle="Italic" Foreground="Red" Text="{Binding ItalicText}" /> </TextBlock.Inlines>

您还可以绑定其他属性:

You can also bind the other properties:

<TextBlock.Inlines> <Run FontWeight="{Binding Weight}" FontSize="{Binding Size}" Text="{Binding LineOne}" /> <Run FontStyle="{Binding Style}" Foreground="Binding Colour}" Text="{Binding LineTwo}" /> </TextBlock.Inlines>

如果您将粗体作为布尔值(例如),则可以通过转换器进行绑定.

You can bind through converters if you have bold as a boolean (say).

更多推荐

在 TextBlock 中格式化文本

本文发布于:2023-05-28 12:28:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/320890.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本   TextBlock

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!