Handling binding between WinRT Image control and ViewModel for local file system images

November 21, 2012
Windows 8 WinRT File System
 

Image class provides a convenient way to display images from Internet


<Image Source="http://lunarfrog.com/myimage.png">

Also Source property accepts ms-appdata and ms-appx URIs, to display local data


<Image Source="ms-appx:///MyFile.png"/>

But for some reason file:// URIs do not supported and it is not possible to use Uri to display, for example, image located in Pictures Library. In this case application needs to load image files manually.

Example 1: loading image in code-behind

XAML


<Image x:Name="MyImage">

Code-behind


var file = await Windows.Storage.KnownFolders.PicturesLibrary.GetFileAsync("MyImage.png");
var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
var img = new BitmapImage();
img.SetSource(fileStream);

MyImage.Source = img;

Example 2: loading image in ViewModel

XAML


<Image Source="{Binding ImgSource}"/>

ViewModel


public class MainPageViewModel : INotifyPropertyChanged
{
   private BitmapImage _imgSource;
   public BitmapImage ImgSource
   {
      get { return _imgSource; }
      set
      {
         _imgSource = value;
         OnPropertyChanged();
      }
   }

   private async void SetImage()
   {
      var file = await Windows.Storage.KnownFolders.PicturesLibrary.GetFileAsync("MyImage.png");
      var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
      var img = new BitmapImage();
      img.SetSource(fileStream);

      ImgSource = img;
   }

   // …
}

blog comments powered by Disqus