Transferring images through WCF and displaying them in a WPF datagrid

What is the best way to transfer an image in a WCF service, and after transferring it, display it in a WPF datagrid?

+6
image wpf wcf
source share
2 answers

I am not saying that this is the only or best solution, but we work like this:

What you need to do:

Create a WCF method that returns the image with some kind of identifier or another. It should return an array of bytes (byte []):

public byte[] GetImage(int id) { // put your logic of retrieving image on the server side here } 

In your data class (objects displayed in the grid) create the Image property, its recipient must call the WCF method and convert the byte array to BitmapImage:

 public BitmapImage Image { get { // here - connection is your wcf connection interface // this.ImageId is id of the image. This parameter can be basically anything byte[] imageData = connection.GetImage(this.ImageId); // Load the bitmap from the received byte[] array using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageData, 0, imageData.Length, false, true)) { BitmapImage bmp = new BitmapImage(); bmp.BeginInit(); bmp.StreamSource = stream; try { bmp.EndInit(); bmp.Freeze(); // helps for performance return bmp; } catch (Exception ex) { // Handle exceptions here } return null; // return nothing (or some default image) if request fails } } } 

In the template of your cell (or somewhere), set the Image control and bind its Source property to the Image property created above:

 <DataTemplate> <!-- Can be a ControlTemplate as well, depends on where and how you use it --> <Image Source={Binding Image, IsAsync=true} /> </DataTemplate> 

The easiest way to not freeze the user interface when retrieving images is to set the IsAsync property to false. But there is much to improve. For example. You can show some loading animation during image loading.

By displaying something at boot time, something else can be done using PriorityBinding (you can read about it here: http://msdn.microsoft.com/en-us/library/ms753174.aspx ).

+8
source share

Can I load a WPF image from a stream? If so, then you can write a WCF service to return the type System.IO.Stream.

0
source share

All Articles