A StringFormat converter for Windows 8 Metro

Some people seem to think that the world has only one language, one currency, and one way to represent a date, a time, or a number. So WinRT comes without a StringFormat option in data binding. I know for sure that I never built a WPF or Silverlight application without extensively using that StringFormat option. Just think about how your calendar or online banking application would look like without the proper content formatting:

"Dear customer, at 3/20/2012 6:23:30 PM the balance of your bank account BE43068999999501 was at -850325, so we will withdraw that amount from your credit card 4417123456789113. Please call +442071311117 for further assistance."

You simply can't get away with that, so I believe that one of the next Metro versions *will* come with string formatting in bindings. In the mean time, we will have to implement formatting in the viewmodel, or help ourselves using a value converter. Here's an example of the latter. It supports two-way bindings, and it doesn't crash when you forget to specify the format:

public class StringFormatConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        // No format provided.
        if (parameter == null)
        {
            return value;
        }

        return String.Format((String)parameter, value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        return value;
    }
}

Just define it as a resource in XAML:

<Page.Resources>
    <local:StringFormatConverter x:Key="StringFormatConverter" />
</Page.Resources>

And use it:

<TextBlock Text="{Binding SomeDateTime, Converter={StaticResource StringFormatConverter}, ConverterParameter='{}{0:dd MMM yyyy}'}" />

It works well against strings, dates, times, and numbers:

Here's the full source. It was built with Visual Studio 11 Express Beta, for the Windows 8 Consumer Preview: U2UConsult.WinRT.StringFormatConverterSample.zip (170,03 kb)

Enjoy!