Monday, August 23, 2010

Creating Custom Formatters for WPF ListView

In the previous post I showed how you can create and bind a ListView using LINQ. Now, if you want to format a value in one of the columns, one way to go around this is using StringFormat. Here is a very good blog entry explaining this.

StringFormat however allows for mostly basic formatting. What if you want to do something more complicated?

As an example, and since I am from Cyprus, I wanted to format an Amount column to display as currency but with the Euro symbol.


To do this, we need to create a new class which will handle the conversion:

namespace Test.Converters
{
    [ValueConversion(typeof(String), typeof(String))]
    public class AmountConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, 
            object parameter, CultureInfo culture)
        {
            return "€" + double.Parse(value.ToString()).ToString("#,#.00", 
            CultureInfo.InvariantCulture);
        }

        public object ConvertBack(object value, Type targetType, 
            object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}

The ConvertBack function is used when you need to go the opposite direction. That is, get the value (for our example) back to a simple double value. For this example, this is not necessary.

Now, we need to instruct our ListView to use the converter. You can insert the converter declaration in your global resources, but I prefer having it local to where I am using it. So, we need to declare the converter. This is done inside the ListView declaration:

    <ListView.Resources>
        <conv:AmountConverter x:Key="AConv" />
    </ListView.Resources>

Where conv is declared in our page/window declaration as:

    xmlns:conv="clr-namespace:Test.Converters"

Now, we simply add the directive to convert the value of a column using the converter:

    <GridViewColumn 
        DisplayMemberBinding="{Binding Amount, Converter={StaticResource AConv}}" 
        Header="Amount" />

Thats it!

No comments:

Post a Comment