Background
In .NET (3.5+) and Silverlight, data that is bound to a control can be easily formatted using StringFormat<code>
. StringFormat
applies standard or custom .NET formatting strings. Here, the property ReleaseDate
is being bound to the Text property of a TextBlock
.
<TextBlock Text="{Binding ReleaseDate, StringFormat=\{0:D\}}" />
Unfortunately, Windows Runtime is missing the StringFormat
capability.
Solution
To workaround this is quite simple. It requires a new class that can be added to your toolkit:
public class StringFormat : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return string.Format(parameter as string, value);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return null;
}
}
Now you can simply reference the class in your XAML, and use it like so:
<Page.Resources>
<local:StringFormat x:Name="StringFormat"/>
</Page.Resources>
...
<TextBlock Text="{Binding ReleaseDate, Converter={StaticResource StringFormat}, ConverterParameter=\{0:D\}}" />
Points of Interest
By creating a class that implements IValueConverter
, any type can be bound to a XAML control without any code behind.