Dutton

How to put a line break in a XAML StringFormat

One of the new features introduced way back in .Net 3.5SP1 was StringFormat. This allows you to define the format of the output if the bound value is a string.

It turns out that this is a lot more efficient than using multiple Runs in TextBlocks to concatenate strings and bound values, so in my quest for "ultimate WPF performance" (TM) this was my latest victim. My old code in a pop-up looked something like this:

<TextBlock>
    <Run Text="{Binding FieldNumber}"/>
    <LineBreak/>
    <Run Text="{Binding FieldValue}"/>
</TextBlock>

But how do you implement the line break using a StringFormat I hear you ask? It turns out you can use the hexadecimal encoded value for a new line

&#x0a;

as follows:

<TextBlock>
  <TextBlock.Text>
    <MultiBinding StringFormat="{}{0}&#x0a;{1}">
      <Binding Path="FieldNumber"/>
      <Binding Path="FieldPath"/>
    </MultiBinding>
  </TextBlock.Text>
</TextBlock>

And there you go... hope this helps.


Share this: