WPF-TextBlock-以编程方式格式化文本

WPF-TextBlock-以编程方式格式化文本,wpf,xaml,styles,Wpf,Xaml,Styles,在TextBlock对象中,您可以按如下方式格式化XAML中的文本: <TextBlock> <Bold>bold text</Bold> random non bold next </TextBlock> 粗体文本随机非粗体下一步 如何以编程方式处理“粗体”标记 我尝试将它们放在text属性中,它只是将它们打印出来(标记打印为文本)。Visual Basic版本: Dim tb As New TextBlock Dim b As

在TextBlock对象中,您可以按如下方式格式化XAML中的文本:

<TextBlock>
    <Bold>bold text</Bold> random non bold next
</TextBlock>

粗体文本随机非粗体下一步
如何以编程方式处理“粗体”标记

我尝试将它们放在text属性中,它只是将它们打印出来(标记打印为文本)。

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版本:


以下是MSDN网站上的代码,我认为这会有所帮助()

XAML

试试这个:


textBlock1.fontwweight=Windows.UI.Text.fontwweights.Bold

谢谢你的两个好答案。两人都投了赞成票。选择我做的一个,因为它是针对我的示例的。更好的解决方案:有人知道像tb.Inlines.Clear()这样的方法吗;Add(Parse(myXamlText))
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);
<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>
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.";