Jump to content

WPF TextBlock StringFormat

Posted on:December 14, 2010 at 01:00 AM

This post is not a hot news, but it may help somebody ;)

Before .NET 3.5 SP1 when I wanted to display formated informations in TextBlock i had to do some workarounds… For example to display coordinates (int x, int y) there were two possibilities (at least):

  1. Create readonly property in the model and bind to it (public string Coordinates {get{ return String.Format(“X:{0} Y:{0}“,x,y);}})
  2. User couple of Label control to show the intended “line”.

Both approaches sux :) But, since .NET 3.5 SP1 there a better solution to that problem :D You can write code like this:

<TextBlock Text="{Binding Date, StringFormat={}{0:MM/dd/yyyy hh:mm tt}}" />

or this:

        <MultiBinding StringFormat="X:{0} Y:{1}">
            <Binding Path="X" />
            <Binding Path="Y" />

Last sample solves my problem. I don’t add additional