Databinding TextBlocks with XAML

I’ve become frustrated lately with trying to databind a list of strings to a textblock. Ie, if I have:

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

And I want the effective end result to be:

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

Or maybe I want something more complex like hyperlinks:

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

Basically what I’m looking for is a ItemsControl that works on TextBlocks (or Spans, etc.), with a Separator template to insert those “, ” in between the items.

Your first instinct might be to use a StackPanel instead, but StackPanel wasn’t made for displaying text. It might fool you initially, but you quickly notice it doesn’t behave anything like text: there’s no proper kerning, RTL, wrapping, or anything else the text classes were made to support.

I’m pretty surprised that WPF doesn’t have anything like this, as it seems like displaying lists as text would be a common enough thing for any app. Unfortunately I’m still not well versed enough in WPF to create such a custom control for myself, and haven’t had a whole lot of time to investigate it.

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

Related Posts