Blog

All Blog Posts

Conditionally Displaying Images when Binding in Silverlight

I have found myself trying to bind records in my XAML code where sometimes I have an image for a record and sometimes I don't. I really want to display a default image if the record doesn't have an image. At other times I want to show an image based on the status of a record (e.g. Started, Pending, Complete).

To accomplish this in Silverlight we have found using Formatters do the trick quite nicely. Here are the steps we have taken to implement an Image Formatter.

1. Create a class that implements the IValueConverter interface.

    public class BusinessImageFormatter : IValueConverter
    {
        public BusinessImageFormatter()
        {
        }

        private string imagePrefix = "http://www.MyApplication.net/images/";

        public object Convert(object value, Type targetType, object parameter,
             System.Globalization.CultureInfo culture)
        {
            string imageSource = "/MyApplication;Component/Assets/Images/BizDefault.png";
            if (value != null)
            {
                string imageValue = value.ToString().ToLower();
                if (imageValue.EndsWith(".png") || imageValue.EndsWith(".jpg"))
                {
                    imageSource = imagePrefix + value.ToString();
                }
            }
            return imageSource;
        }

        public object ConvertBack(object value, Type targetType,
             object parameter, System.Globalization.CultureInfo culture)
        {
            return value;
        }
    }

2. Add this class as a Page Resource in the XAML Add the following to the User Control heading: xmlns:converter="clr-namespace:MyApplication.Helpers"

    <navigation:Page.Resources>
        <converter:BusinessImageFormatter x:Key="ImageFormatter" />
    </navigation:Page.Resources>

 3. When binding use the page resource to call your ImageConverter class.

    <StackPanel Orientation="Horizontal">
        <controls:Viewbox Height="60" Width="60" VerticalAlignment="Center">
            <xImage x:Name="image"
               Source="{Binding busImage, Converter={StaticResource ImageFormatter}}" />
        </controls:Viewbox>
        <TextBlock x:Name="{Binding businessID}" Text="{Binding busName}" />
    </StackPanel>

 The result is that we have complete control on which image is displayed for each image and put rules in place in our Formatter class.

         

Very easy and powerful. Thanks!