代码之家  ›  专栏  ›  技术社区  ›  Chen Kinnrot

通过wcf传递图像并在wpf数据报中显示它们

  •  6
  • Chen Kinnrot  · 技术社区  · 16 年前

    WCF 服务,传递后,将其显示在 WPF 数据网格?

    2 回复  |  直到 10 年前
        1
  •  8
  •   arconaut    16 年前

    我不是说这是唯一或最好的解决方案,但我们的解决方案是这样的:

    你需要做的是:

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

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

    在数据类(网格中显示的对象)中生成属性图像,其getter应调用wcf方法并将字节数组转换为位图图像:

    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
        }
      }
    }
    

    在单元模板(或任何位置)中,放置图像控件并将其源属性绑定到上面创建的图像属性:

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

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

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

        2
  •  0
  •   John Saunders    16 年前

    可以从流中加载WPF图像吗?如果是,那么可以编写wcf服务以返回system.io.stream类型。

    推荐文章