通过WCF传递图像并将其显示在WPF数据网格中

时间:2009-04-23 21:59:18

标签: .net wpf wcf image

WCF服务中传递图片的最佳方式是什么,在传递后,将其显示在WPF数据网格中?

2 个答案:

答案 0 :(得分:8)

我不是说这是唯一或最好的解决方案,但我们的工作方式如下:

您需要做的是:

创建一个WCF方法,该方法将通过某个id或其他方式返回图像。它应该返回字节数组(byte []):

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

在你的数据类(网格中显示的对象)中创建一个属性Image,它的getter应该调用WCF方法并将字节数组转换为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
    }
  }
}

在您的单元格模板中(或在任何地方)放置一个Image控件并将其Source属性绑定到上面创建的Image属性:

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

检索图像时不冻结UI的最简单方法是将IsAsync属性设置为false,就像我一样。但是还有很多需要改进的地方。例如。您可以在加载图像时显示一些加载动画。

使用PriorityBinding可以在加载其他内容时显示内容(您可以在此处阅读:http://msdn.microsoft.com/en-us/library/ms753174.aspx)。

答案 1 :(得分:0)

您可以从流中加载WPF图像吗?如果是这样,那么您可以编写WCF服务以返回System.IO.Stream类型。