User avatar
SL_Rico
Topic Author
Posts: 12
Joined: 03 Jul 2021, 08:18

Accessing Children property of TextBlock

19 Nov 2021, 16:57

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 :)
 
User avatar
sfernandez
Site Admin
Posts: 2991
Joined: 22 Dec 2011, 19:20

Re: Accessing Children property of TextBlock

19 Nov 2021, 17:14

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!"));
 
User avatar
SL_Rico
Topic Author
Posts: 12
Joined: 03 Jul 2021, 08:18

Re: Accessing Children property of TextBlock

19 Nov 2021, 17:17

Perfect, that solves my issue!
Thank you and have a great weekend :)
 
User avatar
sfernandez
Site Admin
Posts: 2991
Joined: 22 Dec 2011, 19:20

Re: Accessing Children property of TextBlock

19 Nov 2021, 17:24

Thank you! Marking this as solved.

Who is online

Users browsing this forum: No registered users and 30 guests