如何在我的 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 中格式化文本
发布评论