Home > C#, MVVM, WinRT > StringFormat converter for Windows Store apps

StringFormat converter for Windows Store apps

26/04/2013

WinRT misses the StringFormat property for data binding. However, we can implement the same behavior using a converter:

public sealed class StringFormatConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (value == null)
            return null;

        if (parameter == null)
            return value;

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

    public object ConvertBack(object value, Type targetType, object parameter, 
        string language)
    {
        throw new NotImplementedException();
    }
}

Its usage is straightforward:

<TextBlock Text="{Binding Name, 
    Converter={StaticResource StringFormatConverter}, 
    ConverterParameter='Welcome, {0}!'}" />

<TextBlock Text="{Binding Amount, 
    Converter={StaticResource StringFormatConverter}, 
    ConverterParameter='{}{0:C}'}" />
Categories: C#, MVVM, WinRT
%d bloggers like this: