Share via


The FormatConverter, and XamlParseExceptions in Microsoft Expression Blend

A converter we very often use and reimplement is the so-called FormatConverter, which takes a string as a value and uses with the converter’s parameter in a call to String.Format. This eases sometimes shortens the XAML by quite a bit when concatenating strings, or can also be used to apply specific formatting to floating point numbers or dates.

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    if (value == null) return null;
    var parm = parameter as string;
    if (string.IsNullOrEmpty(parm)) return value;
    return string.Format(parm, value);

Which is used as follows :

{Binding MyValue, Converter={StaticResource BlendableFormatConverter}, ConverterParameter='{0:0.00} €'}

Note that we escape the target string with single quotes, and that we use the {0} notation to specify the binding’s value we want to format.

The naive implementation for this converter has a major drawback : braces are reserved for XAML markup extensions, and they cause syntax/parsing errors with WPF and Expression Blend. Silverlight 3’s XAML parser being more permissive, the converter compiles and runs fine, but still causes an exception in Expression Blend.

image

The workaround for this is quite simple: replace braces with square brackets in the XAML, and do the reverse in the converter:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    if (value == null) return null;

    var parm = parameter as string;

    if (string.IsNullOrEmpty(parm)) return value;

    return string.Format(parm.Replace('[','{').Replace(']','}'), value);

}

Which is used as follows :

{Binding MyValue, Converter={StaticResource BlendableFormatConverter}, ConverterParameter='[0:0.00] €'}

This trick is simple, works on both frameworks, and will probably enlighten the life of your favorite XAML designer/integrator :)

BlendableFormatConverterDemo.zip