Whats the best way to pass an image in wcf service, and after passing it display it in a wpf datagrid?
Can you load the WPF image from a stream? If so, then you can write the WCF service to return the System.IO.Stream type.
I'm not saying this is the only or the best solution, but we have it working like this:
What you need to do is:
Create a WCF method that would return the image by some id or whatever. It should return byte array (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) make a property Image, its getter should call the WCF method and convert byte array to a 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 your cell template (or wherever) put an 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 simplest way to not make UI freeze when retrieving the images would be setting IsAsync property to false like I did. But there's a lot to improve. E.g. you could show some loading animation while the Image is being loaded.
Showing something while loading something else can be accomplished using PriorityBinding (you can read about it here: http://msdn.microsoft.com/en-us/library/ms753174.aspx).
Say I have a datatable that is bound with datagridview and I want to show host name in first column and in other added coulumns i want to show a gif of cross. Please tell me how to write in C# to view image in datagridview.
Thanks in advance.