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.
Yvan Rodrigues has 30 years of experience in information systems and software development for the industry. He is Senior Concept Designer at
Robotic Assistance Devices
He is a Certified Technician (C.Tech.), a professional designation granted by the Institute of Engineering Technology of Ontario (IETO).
Yvan draws on experience as owner of
Red Cell Innovation Inc.,
Mabel's Labels Inc. as Manager of Systems and Development, the
University of Waterloo as Information Systems Manager, and
OTTO Motors as Senior Systems Engineer and Senior Concept Designer.
Yvan is currently focused on design of embedded systems.