Page 1 of 1

Accessing Children property of TextBlock

Posted: 19 Nov 2021, 16:57
by SL_Rico
Hello everyone :)

I'm trying to add Run elements to a TextBlock element using C# but wasn't able to figure out how until now.
In XAML a Run element can be added without any problems, so I assume it should be possible in C# as well, right?

My XAML code looks like this and I'd like to create the exact same structure using C# dynamically at runtime.
<TextBlock FontSize="16" Foreground="White">
    <Run FontWeight="Bold"
         Foreground="DeepSkyBlue"><![CDATA[Ally Attacker ]]></Run>
    <Run><![CDATA[hit's ]]></Run>
    <Run FontWeight="Bold"
         Foreground="OrangeRed"><![CDATA[Enemy Defender ]]></Run>
    <Run><![CDATA[with ]]></Run>
    <Run FontWeight="Bold"><![CDATA[123 ]]></Run>
    <Run><![CDATA[Armor Damage & ]]></Run>
    <Run FontWeight="Bold"><![CDATA[321 ]]></Run>
    <Run><![CDATA[HP Damage | ]]></Run>
    <Run FontWeight="Bold"
         Foreground="DarkGoldenrod"
         TextDecorations="Underline"><![CDATA[Punch]]></Run>
    <Run><![CDATA[ (86%)]]></Run>
</TextBlock>
Any help is appreciated :)

Re: Accessing Children property of TextBlock

Posted: 19 Nov 2021, 17:14
by sfernandez
Hello,

TextBlock exposes the Inlines collection where you can add inline children in code:
textBlock.Inlines.Add(new Run("Hello"));
textBlock.Inlines.Add(new Run("World!"));

Re: Accessing Children property of TextBlock

Posted: 19 Nov 2021, 17:17
by SL_Rico
Perfect, that solves my issue!
Thank you and have a great weekend :)

Re: Accessing Children property of TextBlock

Posted: 19 Nov 2021, 17:24
by sfernandez
Thank you! Marking this as solved.