2013-03-04 68 views
0

我有一个列表框与图片:绑定图像并保存为缓存文件夹

<Image Margin="0" Source="{Binding Path=ImgUrl}" HorizontalAlignment="Stretch" Width="80" Height="80" 
               Tag="{Binding idStr}" OpacityMask="{x:Null}" Stretch="Fill"/> 

,我想,当我将它绑定,将图像保存到我的磁盘缓存的问题,并在下一次会检查图像是否存在并将其从磁盘中取出。有可能做这样的事情吗? 下载图像 - >保存到磁盘 - >使图像作为图像源

回答

1

您可以使用专门的binding converter将每个图像保存到文件。

下面的示例代码显示了这种转换器的基本结构。您将不得不添加一些错误处理,当然您需要定义从图像URI到本地文件路径的映射。您也可以支持System.Uri作为替代来源类型。

public class ImageConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     var result = value; 
     var imageUrl = value as string; 

     if (imageUrl != null) 
     { 
      var buffer = (new WebClient().DownloadData(imageUrl)); 

      if (buffer != null) 
      { 
       // create an appropriate file path here 
       File.WriteAllBytes("CachedImage.jpg", buffer); 

       var image = new BitmapImage(); 
       result = image; 

       using (var stream = new MemoryStream(buffer)) 
       { 
        image.BeginInit(); 
        image.CacheOption = BitmapCacheOption.OnLoad; 
        image.StreamSource = stream; 
        image.EndInit(); 
       } 
      } 
     } 

     return result; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotSupportedException(); 
    } 
} 

你会使用转换器在你的绑定是这样的:

<Image Source="{Binding Path=ImgUrl, 
       Converter={StaticResource ImageConverter}}" ... /> 
相关问题