How to Display Byte Array Image in RadGridView Column
Environment
Product Version | 2019.1.220 |
Product | RadGridView for WPF |
Description
How to display an image from a byte array in RadGridView when auto generated columns are enabled.
Solution
-
Implement an IValueConverter that converts the byte array to an ImageSource object.
public class ByteArrayToImageSourceConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { byte[] imageData = (byte[])value; BitmapImage biImg = new BitmapImage(); MemoryStream ms = new MemoryStream(imageData); biImg.BeginInit(); biImg.StreamSource = ms; biImg.EndInit(); ImageSource imgSrc = biImg as ImageSource; return imgSrc; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }
-
Define a DataTemplate in XAML that contains an Image element bound to the byte array. And use the converter to convert the array to an ImageSource.
<Window.Resources> <local:ByteArrayToImageSourceConverter x:Key="ByteArrayToImageSourceConverter" /> <DataTemplate x:Name="ImageCellTemplate"> <Image Source="{Binding MyImageByteArray, Converter={StaticResource ByteArrayToImageSourceConverter}}" /> </DataTemplate> </Window.Resources>
-
Subscribe to the AutoGeneratingColumn event of RadGridView and in the event handler check if the column is the one showing the byte array. In this case, set the column's CellTemplate property.
private void RadGridView_AutoGeneratingColumn(object sender, GridViewAutoGeneratingColumnEventArgs e) { if (e.Column.UniqueName == "MyImageByteArray") { var dataColumn = (GridViewDataColumn)e.Column; dataColumn.CellTemplate = (DataTemplate)this.Resources["ImageCellTemplate"]; } }