14

I know in XAML we can do...

<TextBlock FontSize="18">
   This is my text <LineBreak/>
   <Run FontSize="24" FontWeight="Bold">My big bold text</Run>
</TextBlock>

Question is, how can I assign a Run into a text (string) property, programmatically?

svick
  • 236,525
  • 50
  • 385
  • 514
Néstor Sánchez A.
  • 3,848
  • 10
  • 44
  • 68

1 Answers1

25

If you look at TextBlock you will see that ContentProperty is set to Inlines

[Localizability(LocalizationCategory.Text), ContentProperty("Inlines")]
public class TextBlock : FrameworkElement, ...

This means that you will add Inline elements to the property Inlines for everyting added between the opening and closing tag of TextBlock.

So the c# equivalent to your Xaml is

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);
Fredrik Hedblad
  • 83,499
  • 23
  • 264
  • 266
  • 2
    No need for a decompiler, the documentation can tell you that too (both in the form of an attribute and prose). – svick Jun 06 '12 at 00:50
  • @svick: Very true. I used reflector just to be able to paste it in. But that surely isn't the only way, I'll remove that part from the answer – Fredrik Hedblad Jun 06 '12 at 00:54
  • @svick: Also, I'll take the chance to learn something here. I can see it at MSDN but what did you mean by attribute or prose? – Fredrik Hedblad Jun 06 '12 at 00:56
  • 1
    I meant that you can either look at the syntax section and see the `[ContentPropertyAttribute]`, or read the Remarks: “A `TextBlock` can contain a string in its `Text` property or `Inline` flow content elements […] in its `Inlines` property.” – svick Jun 06 '12 at 00:59
  • BTW, I think this is a good example of code where object and collection initializers could make it more readable. – svick Jun 06 '12 at 01:01