Telerik blogs

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 project with the converter working.  I threw a few sample pictures into the default website Images folder for you to play with. 

Happy coding!


About the Author

Evan Hutnick

works as a Developer Evangelist for Telerik specializing in Silverlight and WPF in addition to being a Microsoft MVP for Silverlight. After years as a development enthusiast in .Net technologies, he has been able to excel in XAML development helping to provide samples and expertise in these cutting edge technologies. You can find him on Twitter @EvanHutnick.

Related Posts

Comments

Comments are disabled in preview mode.