Andrej Tozon's blog

In the Attic

NAVIGATION - SEARCH

Windows Store apps: the case of missing StringFormat or Binding on the Run

If your previous developer experience include developing for other XAML technologies and you’re moving into the Windows Store apps space, you’ve already noticed that a lot of things you were used to in other techs, are missing from your Windows Store app development experience. One example being there’s no more StringFormat property available in your Binding markup construct. You may have been used to writing something like:

<TextBlock Text="{Binding Name, StringFormat='Name: \{0\}'}" />

(that would bind your TextBlock to the Name property, outputting “Name: [property value]” to the UI)

With StringFormat missing from WinRT’s XAML Binding, you have two options:

1. Create a StringFormat value converter and handle your string formatting there.

2. Break down your text into smaller chunks of text and bind those to the Runs, which are part of your TextBlock:

<TextBlock Style="{StaticResource BodyTextStyle}" TextWrapping="NoWrap">
  <Run Text="Name: " />
  <Run Text="{Binding Name}" Foreground="Red" />
</TextBlock>

Yes, Runs are bindable!

Not only will Runs inherit styling attributes from their parent TextBlock, you can override them in whole, or just parts of it (like changing color only, etc.) And you make your TextBlock “bind” to more than one property in one go, something not possible with StringFormat or converter workaround.

Pretty cool.