在 TextBlock 中格式化文本 [英] Formatting text in a TextBlock

查看:46
本文介绍了在 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 中格式化文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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