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}}" ... /> 
相關問題