Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / XAML

A StringFormat Replacement for Windows RT

5.00/5 (2 votes)
18 Apr 2013CPOL 9.9K  
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<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: 

C#
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:

XML
    <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. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)