.netvisual-studio-2010silverlight-4.0

Problem with image from server in Silverlight


I have a problem with a image when trying to display it. In my project I have a Class which has a "public String Image" attribute.

I have a web server locally which returns me a collection of Class. When I look in debug mode at the Image attribute it show me the correct URL (if I paste the URL in browser it show me the image) but the image isn't display. If instead I put any URL from an image from internet it shows me the image.

I don't understand why the image from local server isn't shown in Silverlight app, but in browser it is. The code used in Silverlight is:

<Image Name="photoImage" Source="{Binding Image}" Margin="30,10,30,10" />

Thanks.


Solution

  • Try using this converter:

    public class RelativeImageSourceConverter : IValueConverter
    {
    
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null) { return null; }
            var originalString = value.ToString();
            if (!Uri.IsWellFormedUriString(originalString, UriKind.RelativeOrAbsolute)) { return null; }
            var imageUri = new Uri(originalString, UriKind.RelativeOrAbsolute);
            if (!imageUri.IsAbsoluteUri)
            { 
                var hostUri = Application.Current.Host.Source;
                imageUri = new Uri(hostUri, originalString);
            }
            var image = new BitmapImage(imageUri);
            return image;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }