Developing for Modern Windows

Tips, tricks, and guides for developing on modern Windows platforms

Quick Tip: Run-on TextBlock in XAML (Universal Apps)

When you want to bind some data to a textblock, you do so like this:


<TextBlock Text="{Binding MyTextProperty}"/>

 

And, having set MyTextProperty in my data model to "hello world", I get this:

But what if you want to format your text in more complex ways? One great tool you may not know about is the <Run> XAML element. <Run> lets you chain (or run-on) multiple pieces of text.

Here's an example that prints the score to a soccer match in a single TextBlock with multiple bound strings:


<TextBlock>
<Run Text="{Binding TeamOne.Name}"/>;
<Run Text=" "/>
<Run Text="{Binding TeamOne.Score}"/>;
<Run Text=" - "/>
<Run Text="{Binding TeamTwo.Score}"/>
<Run Text=" "/>
<Run Text="{Binding TeamTwo.Name}"/>
</TextBlock>

This gives a (somewhat unrealistic) result like this:

To achieve the same result without <Run> you might create multiple TextBlocks with different bindings. By keeping the various bindings within the same TextBlock you make it easier to change the style and positioning of the text (i.e. you only need to change the font once to change all the text – though you can style each <Run> block separately if you need to).

Tags: , , ,

Leave a Reply

Your email address will not be published.