Oct 17, 2011

Binding to Image Path in Isolated Storage

Bind Image Source to web address is not problem, it will works well... until You don't care about performance. Problem will appear if You want to cache images. Isolated storage is only way to store downloaded files in Silverlight not matter Browser or Windows Phone. Not so difficult to download image file from Internet and save to Isolated Storage, but how to use it in Silverlight Page?

Well, lets try to figure out. First define image converter:

  1. public class IsoImageConverter : IValueConverter    
  2. {    
  3.     //Convert Data to Image when Loading Data    
  4.     public object Convert(object value, Type targetType, object parameter,    
  5.         System.Globalization.CultureInfo culture)    
  6.     {    
  7.         var bitmap = new BitmapImage();    
  8.         try    
  9.         {    
  10.             var path = (string)value;    
  11.             if (!String.IsNullOrEmpty(path))  
  12.             {    
  13.                 using (var file = LoadFile(path))    
  14.                 {    
  15.                     bitmap.SetSource(file);    
  16.                 }    
  17.             }    
  18.         }    
  19.         catch    
  20.         {    
  21.         }    
  22.         return bitmap;    
  23.     }    
  24.     
  25.     private Stream LoadFile(string file)    
  26.     {    
  27.         using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())    
  28.         {    
  29.             return isoStore.OpenFile(file, FileMode.Open, FileAccess.Read);    
  30.         }    
  31.     }    
  32.         
  33.     public object ConvertBack(object value, Type targetType, object parameter,    
  34.         System.Globalization.CultureInfo culture)    
  35.     {    
  36.         throw new NotImplementedException();    
  37.     }    
  38. }  

Next define link in App.xaml for use in XAML code

  1. <local:IsoImageConverter x:Key="IsoImageCoverter"/>  

And finally bind to string path to Isolated Storage image file

  1. <Image Source="{Binding ImagePath, Converter={StaticResource IsoImageCoverter}}"/>