Generic IValueConverter for Silverlight or WPF

by Dean 24. January 2009 10:37

When using the GridView in ASP.NET it is very handy to be able to include a ‘FormatString’ attribute to bound columns and the like – enabling you to display those dates, currency values, numbers etc in a more readable form.

I was surprised that Silverlight or WPF doesn't offer this out of the box, and I couldn't find any ‘obvious’ answers when I googled the subject,

Therefore, I created a simple IValueConverter to achieve the same result.

Here's the code for the converter:

namespace CBSSilverlight
{
    public class FormatStringValueConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, 
            CultureInfo culture)
        {
            if (value == null)
                return string.Empty;
            return !string.IsNullOrEmpty(parameter.ToString()) ? string.Format(culture, 
                parameter.ToString(), value) : value.ToString();
        }
 
        public object ConvertBack(object value, Type targetType, object parameter, 
            CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

As you can see, it doesn't support 2 way conversions, so it’s only really appropriate for read-only grids.

So in order to use this IValueConverter, the first step is to add the class with the code above into your VS2008 project.

Next, we need to include it as a static resource in our UserControl by adding the following to our XAML (don't forget to reference your namespace in the UserControl declaration)

 
<UserControl.Resources>
    <CBSSilverlight:FormatStringValueConverter x:Key="FormatConverter" />
</UserControl.Resources>
 

Now we can use the IValueConverter in our column declarations:

 

<data:DataGrid HorizontalAlignment="Left" 
               Grid.Row="1" Margin="0,0,0,1" 
               d:LayoutOverrides="Height" 
               ItemsSource="{Binding}" 
               AutoGenerateColumns="False" 
               MaxHeight="370" 
               SelectionChanged="SelectionChanged" >
    <data:DataGrid.Columns>
        <data:DataGridTextColumn 
            Header="Name" 
            Binding="{Binding Path=Name}" />
        <data:DataGridTextColumn 
            Header="Order Date" 
            Binding="{Binding Converter={StaticResource FormatConverter}, 
                ConverterParameter=\{0:dd-MMM-yy HH:mm\}, Path=OrderDate}"/>
        <data:DataGridTextColumn 
            Header="Total" 
            Binding="{Binding Converter={StaticResource FormatConverter}, 
                ConverterParameter=\{0:£0.00\}, Path=ItemsTotal}" />
        <data:DataGridTextColumn 
            Header="Discount" 
            Binding="{Binding 
            Path=DiscountCode}"/>
        <data:DataGridTextColumn 
            Header="Potage" 
            Binding="{Binding Converter={StaticResource FormatConverter}, 
            ConverterParameter=\{0:£0.00\}, Path=Postage}"/>
        <data:DataGridTextColumn 
            Header="Total" 
            Binding="{Binding Converter={StaticResource FormatConverter}, 
                ConverterParameter=\{0:£0.00\}, Path=GrandTotal}"/>
        <data:DataGridTextColumn 
            Header="Post" 
            Binding="{Binding Path=PostageType}"/>
        <data:DataGridTextColumn 
            Header="Num." 
            Binding="{Binding Path=TotalOrders}"/>
        <data:DataGridTextColumn 
            Header="First" 
            Binding="{Binding Converter={StaticResource FormatConverter}, 
            ConverterParameter=\{0:dd-MMM-yy\}, Path=FirstShippedOrder}" />
        <data:DataGridTextColumn 
            Header="Last" 
            Binding="{Binding Converter={StaticResource FormatConverter}, 
            ConverterParameter=\{0:dd-MMM-yy\}, Path=LastShippedOrder}" />
        <data:DataGridTextColumn 
            Header="Min. Val." 
            Binding="{Binding Converter={StaticResource FormatConverter}, 
            ConverterParameter=\{0:£0.00\}, Path=MinOrderValue}" />
        <data:DataGridTextColumn 
            Header="Max. Val." 
            Binding="{Binding Converter={StaticResource FormatConverter}, 
            ConverterParameter=\{0:£0.00\}, Path=MaxOrderValue}" />
    </data:DataGrid.Columns>
</data:DataGrid>

As you can see, the converter elegantly handles Dates, Money and anything else you can dream of, just like in the ASP.NET GridView.

And here’s a screen-shot below of the converter in action

formatgrid

As you can see – Dates, Date/Times and Money columns look great.

If anyone has any comments, or suggests any improvements – please feel free to add a comment below

Thanks

Dean Chalk

Tags: , ,

DataBinding | Silverlight

Comments


January 24. 2009 10:49
trackback
Trackback from DotNetKicks.com

Generic IValueConverter for Silverlight or WPF


January 26. 2009 01:10
trackback
Trackback from Community Blogs

Silverlight Cream for January 25, 2009 -- #497


January 27. 2009 01:51
ianwij
In .NET 3.5 SP1, WPF now has Binding.StringFormat. Hopefully Silverlight 3 will get this too.


Kampanye Damai Pemilu Indonesia 2009
Great article..


thanks for sharing..

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Most comments

Tom Tom
1 comments
Derek Lakin Derek Lakin
1 comments
gb United Kingdom
Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010 ButtonChrome.com