WPF TextBlock StringFormat
WPF TextBlock StringFormat
1min read
This post is not a hot news, but it may help somebody ;)
Before .NET 3.5 SP1 when I wanted to display formatted information in TextBlock I had to do some workarounds… For example to display coordinates (int x, int y) there were two possibilities (at least):
- Create readonly property in the model and bind to it (public string Coordinates {get{ return String.Format(“X:{0} Y:{0}”,x,y);}})
- User couple of Label control to show the intended “line”.
Both approaches suck :) But, since .NET 3.5 SP1 there is 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:
<TextBlock> <TextBlock.Text> <MultiBinding StringFormat="X:{0} Y:{1}"> <Binding Path="X" /> <Binding Path="Y" /> </MultiBinding> </TextBlock.Text></TextBlock>Last sample solves my problem, and I don’t need to add any additional properties.