如何以编程方式将"运行"分配给文本属性?

Nés*_* A. 10 c# wpf xaml

我知道在XAML中我们可以做到......

<TextBlock FontSize="18">
   This is my text <LineBreak/>
   <Run FontSize="24" FontWeight="Bold">My big bold text</Run>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

问题是,如何以编程方式将Run分配给文本(字符串)属性?

Fre*_*lad 19

如果你看,TextBlock你会看到ContentProperty设置为Inlines

[Localizability(LocalizationCategory.Text), ContentProperty("Inlines")]
public class TextBlock : FrameworkElement, ...
Run Code Online (Sandbox Code Playgroud)

这意味着您将Inline在属性中添加元素,Inlines以便在开始和结束标记之间添加每个元素TextBlock.

所以c#等同于你的Xaml

TextBlock textBlock = new TextBlock();
textBlock.FontSize = 18;
textBlock.Inlines.Add("This is my text");
textBlock.Inlines.Add(new LineBreak());
Run run = new Run("My big bold text");
run.FontSize = 24;
run.FontWeight = FontWeights.Bold;
textBlock.Inlines.Add(run);
Run Code Online (Sandbox Code Playgroud)

  • 不需要反编译器,文档也可以告诉你(以属性和散文的形式). (2认同)