Databinding TextBlocks with XAML

I’ve be­come frus­trated lately with try­ing to data­bind a list of strings to a textblock. Ie, if I have:

string[] mytext = new string[] { "a", "b", "c" };

And I want the ef­fec­tive end re­sult to be:

<TextBlock>a, b, c</TextBlock>

Or maybe I want some­thing more com­plex like hy­per­links:

<TextBlock>
   <Hyperlink>a</Hyperlink>,
   <Hyperlink>b</Hyperlink>,
   <Hyperlink>c</Hyperlink>
</TextBlock>

Ba­si­cally what I’m look­ing for is a Item­sCon­trol that works on TextBlocks (or Spans, etc.), with a Sep­a­ra­tor tem­plate to in­sert those “, ” in be­tween the items.

Your first in­stinct might be to use a Stack­Panel in­stead, but Stack­Panel wasn’t made for dis­play­ing text. It might fool you ini­tially, but you quickly no­tice it doesn’t be­have any­thing like text: there’s no proper kern­ing, RTL, wrap­ping, or any­thing else the text classes were made to sup­port.

I’m pretty sur­prised that WPF doesn’t have any­thing like this, as it seems like dis­play­ing lists as text would be a com­mon enough thing for any app. Un­for­tu­nately I’m still not well versed enough in WPF to cre­ate such a cus­tom con­trol for my­self, and haven’t had a whole lot of time to in­ves­ti­gate it.

Posted on March 02, 2009 in .NET Framework, C#, Coding, WPF, XAML

Related Posts