Quick and painless Byte Array to Image converter for RadGridView for Silverlight
Posted by: the telerik blogs,
on 13 Oct 2009 |
View original | Bookmarked: 0 time(s)
We received a question today in regards to a binding issue with RadGridView, or rather an issue with an Image in a custom cell template that the customer was trying to bind to a custom value. They had the basic setup right:
<DataTemplate> <Image Source="{Binding ImageData}" /> </DataTemplate>
But something wasn't quite working right. After doing a little digging, we found that they weren't sending a URI to the Image but rather a byte array. Unfortunately, the Image control in Silverlight doesn't quite know how to pick up on this so you need to convince it- with a converter.
With a little bit of coding magic, and knowledge of how the Image control works, we came up with the following:
public class ByteArrayToImageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { byte[] byteBlob = value as byte[]; MemoryStream ms = new MemoryStream(byteBlob); BitmapImage bmi = new BitmapImage(); bmi.SetSource(ms); return bmi; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } Since the Image control allows you to use a BitmapImage as an ImageSource, this turns that byte array into a BitmapImage and returns it to the custom cell template in RadGridView. The new datatemplate only requires a minor modification:
<DataTemplate> <Image Source="{Binding ImageData, Converter={StaticResource ByteToImageConverter}}" /> </DataTemplate> And you're all set. Just so you can see it in action, here is a sample projectwith the converter working. I threw a few sample pictures into the default website Images folder for you to play with.
Happy coding!