WPF - TextBlock - 以编程方式格式化文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1797958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF - TextBlock - Format Text Programmatically
提问by Vaccano
In the TextBlock object you can format the text in the XAML like this:
在 TextBlock 对象中,您可以像这样设置 XAML 中的文本格式:
<TextBlock>
<Bold>bold text</Bold> random non bold next
</TextBlock>
How do you do the "Bold" tags programmatically?
您如何以编程方式执行“粗体”标签?
I tried just putting them in the text property and it just printed them out (the tags were printed as text).
我试着把它们放在 text 属性中,它只是把它们打印出来(标签被打印为文本)。
回答by Wade73
Here is the code from the MSDN website, which I think will help (http://msdn.microsoft.com/en-us/library/system.windows.controls.textblock.aspx).
这是来自 MSDN 网站的代码,我认为它会有所帮助(http://msdn.microsoft.com/en-us/library/system.windows.controls.textblock.aspx)。
XAML
XAML
<TextBlock Name="textBlock1" TextWrapping="Wrap">
<Bold>TextBlock</Bold> is designed to be <Italic>lightweight</Italic>,
and is geared specifically at integrating <Italic>small</Italic> portions
of flow content into a UI.
</TextBlock>
<Button Width="100" Margin="10">Click Me</Button>
<TextBlock Name="textBlock2"
TextWrapping="Wrap" Background="AntiqueWhite" TextAlignment="Center"
>
By default, a TextBlock provides no UI beyond simply displaying its contents.
</TextBlock>
<Button Width="100" Margin="10">Click Me</Button>
C#
C#
TextBlock textBlock1 = new TextBlock();
TextBlock textBlock2 = new TextBlock();
textBlock1.TextWrapping = textBlock2.TextWrapping = TextWrapping.Wrap;
textBlock2.Background = Brushes.AntiqueWhite;
textBlock2.TextAlignment = TextAlignment.Center;
textBlock1.Inlines.Add(new Bold(new Run("TextBlock")));
textBlock1.Inlines.Add(new Run(" is designed to be "));
textBlock1.Inlines.Add(new Italic(new Run("lightweight")));
textBlock1.Inlines.Add(new Run(", and is geared specifically at integrating "));
textBlock1.Inlines.Add(new Italic(new Run("small")));
textBlock1.Inlines.Add(new Run(" portions of flow content into a UI."));
textBlock2.Text =
"By default, a TextBlock provides no UI beyond simply displaying its contents.";
回答by kenwarner
Visual Basic Version:
Visual Basic 版本:
Dim tb As New TextBlock
Dim b As New Bold
b.Inlines.Add(New Run("bold text"))
tb.Inlines.Add(b)
tb.Inlines.Add(New Run("random non bold text"))
C# Version:
C# 版本:
TextBlock tb = new TextBlock();
var bold = new Bold(new Run("Bold Text"));
tb.Inlines.Add(bold);
var normal = new Run("Normal Text"));
tb.Inlines.Add(normal);
回答by FanTasteYou
try this:
尝试这个:
textBlock1.FontWeight = Windows.UI.Text.FontWeights.Bold;
textBlock1.FontWeight = Windows.UI.Text.FontWeights.Bold;