Search code examples
xamlwindows-8

Converter failed to convert value of type 'Windows.Foundation.String' to type 'ImageSource'


This is for my Windows 8 app:

In my object I have a string property that contains the path of the images I want to use.

public String ImagePath

In my XAML I have set up an Image tag with the following binding:

<Image Source="{Binding ImagePath}" Margin="50"/>

When I reference an image that I've included in my project (in the Asset folder) the image displays correctly. The path is: Assets/car2.png

However, when I reference an image that the user selects (using the FilePicker) I get an error (and no image). The path is: C:\Users\Jeff\Pictures\myImage.PNG

Converter failed to convert value of type 'Windows.Foundation.String' to type 'ImageSource'

Just to add a little more info. When I use the file picker I am converting the file location to a URI:

        Uri uriAddress =  new Uri(file.Path.ToString());
        _VM.vehicleSingle.ImagePath = uriAddress.LocalPath;

Update:

I'm also saving this image path to isolated storage. I think this is where the issue is. I'm able to save the path of the file selected, but when I try to bind to it when I'm reloading the Isolated Storage it doesn't work.

So if I can't use an image outside of the application directory. Is there a way I can save that image and add it to the directory?

I tried creating a BitmapImage property to my model but now I'm getting errors stating that it can't serialize a BitmapImage.


Solution

  • You should Use Converter

    public class ImageConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                MemoryStream memStream = new MemoryStream((byte[])value,false);
                BitmapImage empImage = new BitmapImage();
                empImage.SetSource(memStream);
                return empImage;
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }