Value Converter for Binding Images in ListView for Windows Store App

823 views Asked by At

I'm trying to bind images from local/isolated storage to a ListView in my Windows 8.1 store app. The paths (or file names) are stored in Objects in an ObservableCollection fetched from a database.

I might be thinking too simple here but understanding the following "strange" behavior would be the key to getting the images to my ListView. I did find some examples for image binding using value converters but they were for Silverlight apps.

-

Working

Trying to bind an image from isolated storage to an ImageSource in XAML this works:

In the page

<ImageBrush ImageSource="{Binding ImagePath}" />

And in the ViewModel

ImagePath = "ms-appdata:///local/" + _currentCustomer.ImgPath;

-

Not Working

Yet the following (which would help me implementing my ListView) does not work although it seems to produce the exact same result for the XAML ImageSource binding (ms-appdata:///local/image.jpg):

In the page (ImgPath being a property of the customer object, basically the file name)

<ImageBrush ImageSource="{Binding currentCustomer.ImgPath, Converter={StaticResource imageFileConverter}}" />

and in the ViewModel

public class ImageFileConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        string fileName = value as string;
        if (fileName != null)
        {
            String imagePath = "ms-appdata:///local/" + fileName;
            return imagePath;
        }
        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

and in App.xaml

<converters:ImageFileConverter:  x:Key="imageFileConverter"/>

-

What is the difference, or (better) what needs to be done?

1

There are 1 answers

0
AudioBubble On BEST ANSWER

As I could not continue without this I kept studying and figured it out. If set programmatically, the ImageSource needs provided as BitmapImage. The converter needs to be changed as follows:

public class ImageFileConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        string fileName = value as string;

        if (fileName != null)
        {
            BitmapImage bitmap = new BitmapImage();
            bitmap.UriSource = new Uri("ms-appdata:///local/" + fileName);
            return bitmap;
        }
        return null;
    }
    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}