Silverlight IValueConverter for Image Urls

By Robbe Morris

Simply bind your Image Url string property of your data class to the Source property of the Image class using the IValueConverter. At the time of this writing, Silverlight did not support rendering .gif images.

namespace MyXamlSpace.Xaml
{
    public class ImageUrlConverter : IValueConverter
    {
         object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
             try
            {
                 // May want to validate url for image types that are supported in Silverlight.
                 // if (!ImageValidator.IsImageFileNameSupported((string)value)) return null;
                 return new BitmapImage(new Uri((string)value, UriKind.RelativeOrAbsolute));
             }
             catch { }
            return null;
        }
         
         object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
             return null;
        }
     }
}

//  Xaml

<UserControl x:Class="Tutorial.Window1"
    
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    
xmlns:XAMLConverters="clr-namespace:XAMLConverters;assembly=XAMLConverters" >

<Window.Resources>
         <XAMLConverters:ImageUrlConverter x:Key="imageUrlConverter" />
</Window.Resources>

    <Image Source="{Binding ImageUrl, Converter={StaticResource imageUrlConverter}, Mode=TwoWay}"    />

</UserControl>

Silverlight IValueConverter for Image Urls  (4010 Views)