65.9K
CodeProject is changing. Read more.
Home

A StringFormat Replacement for Windows RT

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

Apr 17, 2013

CPOL
viewsIcon

9940

A simple but effective way for format bound data in XAML with the Windows Runtime

Background 

In .NET (3.5+) and Silverlight, data that is bound to a control can be easily formatted using StringFormat. 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
    {
        /// <summary>
        /// Converts the specified value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="targetType">Type of the target.</param>
        /// <param name="parameter">The parameter.</param>
        /// <param name="language">The language.</param>
        /// <returns>The formatted value.</returns>
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            return string.Format(parameter as string, value);
        }  

        /// <summary>
        /// Converts the value back.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="targetType">Type of the target.</param>
        /// <param name="parameter">The parameter.</param>
        /// <param name="language">The language.</param>
        /// <returns>The original value.</returns>
        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            // This does not need to be implemented for simple one-way conversion.
            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.