c# - 格式化 TextBlock 中的文本

标签 c# wpf wpf-controls

如何在我的 WPF 应用程序中实现 TextBlock 控件内文本的格式设置?

例如:我希望某些单词用粗体显示,其他单词用斜体显示,还有一些用不同的颜色显示,就像这个例子:

enter image description here

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

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

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

最佳答案

您需要使用 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>

绑定(bind):

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

您还可以绑定(bind)其他属性:

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

如果您将粗体设置为 bool 值(例如),则可以通过转换器进行绑定(bind)。

关于c# - 格式化 TextBlock 中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5263055/

相关文章:

c# - 如何通过更改文本来更改组合框中的下拉项?

c# - 如何知道 wpf 应用程序是否在终端服务 session 中?

c# - IEnumerable 的 MVC3 编辑器模板不会在 @Html.LabelFor 中生成 'for' 属性

c# - 巴克莱加密 asp.net (VB to c#)

c# - Postgresql/npgsql 在使用丹麦字母时无法写入

wpf - MVVM 灯光和组合框

c# - 从串口读取字节

c# - 如何分离 View 数据和 ViewModel 数据?

wpf - Canvas 中路径的动画填充颜色

wpf - 在 ScrollViewer 中平移 Canvas 的内容