Reputation: 7900
I have a ListBox with Image :
<Image Margin="0" Source="{Binding Path=ImgUrl}" HorizontalAlignment="Stretch" Width="80" Height="80"
Tag="{Binding idStr}" OpacityMask="{x:Null}" Stretch="Fill"/>
And i want that when i bind it it will save the image to my disk for cache issues,and the next time it will check if the image exist and take it from the disk. It is possible to do something like this? Download image-> Save to disk -> make image as image source
Upvotes: 0
Views: 259
Reputation: 128087
You could use a specialized binding converter that saves each image to file.
The sample code below shows the basic structure of such a converter. You will have to add some error handling and of course you need to define a mapping from image URIs to local file paths. You may also support System.Uri
as alternative source type.
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();
}
}
You would use that converter in your binding like this:
<Image Source="{Binding Path=ImgUrl,
Converter={StaticResource ImageConverter}}" ... />
Upvotes: 1