28 March 2011

XAML - Value converter

In XAML, you can use value converters to convert a bound business data value into a GUI-usable value using a class like this one:

public class CurrencyConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) =>
        ((double)value).ToString("C");

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) =>
        double.Parse((string)value);
}

A converter must be put in the resources like so:

<this:CurrencyConverter x:Key="CurrencyConverter" />

You can put it in App.xaml for project-wide usage.

To be then included in a binding like this.
You can also pass it a parameter if you like:

{Binding Amount, Converter={StaticResource CurrencyConverter}}
{Binding Amount, Converter={StaticResource CurrencyConverter}, ConverterParameter=EUR}

The parameter is passed as a string.
If you want to pass something else, you can use a markup extension.

No comments:

Post a Comment