Search code examples
c#wpfimagereturn-typeivalueconverter

Converter to return different types?


I have a List<Employee>. Each Employee has a byte[] storing a picture (or null). I need to somehow bind this byte array to an image control on a content template I'm using, or if the Employee doesn't have a picture I want to display a local jpg file. The way I've come up with is to define a converter that will return either the BitmapImage (return type from GetImageFromByteArray() method) or a string (the path of the filename). This obviously means that this method is capable of returning two types, but I wouldn't have thought this was a problem seeing as though I've specified the return type as object.

Anyway, here's my C#:

public class GuidToImageConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                Guid id = new Guid(value.ToString());
                Employee employee = Employees.SingleOrDefault(o => o.Id.Equals(id));
                return employee.Picture != null ? GetImageFromByteArray(employee.Picture) : "/Resource/images/silhouette.jpg";
            }

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

And used in the XAML like so:

    <local:GuidToImageConverter x:Key="GuidToImageConverter"/>

    <local:OrientedGroupHeaderContentTemplateSelector x:Key="GroupHeaderContentTemplateSelector">
        <!-- Default templates: -->
        <local:OrientedGroupHeaderContentTemplateSelector.HorizontalMonthViewDateTemplate>
            <DataTemplate>
                <Image Width="60" Height="60" Margin="5 0 10 0" HorizontalAlignment="Left" Stretch="UniformToFill" Source="{Binding Path=Name.Id, Converter={StaticResource GuidToImageConverter}, ConverterParameter=1}" />
            </DataTemplate>
        </local:OrientedGroupHeaderContentTemplateSelector.HorizontalMonthViewDateTemplate>
    </local:OrientedGroupHeaderContentTemplateSelector>

The error:

"Error 1 - Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Windows.Media.Imaging.BitmapImage' and 'string'"

I understand that this would probably not be an issue if a proper MVVM structure was in place but it's not feasible at the moment to change it all.


Solution

  • Change the return statement to this to make it work:

    if(employee.Picture != null)
        return GetImageFromByteArray(employee.Picture)
    return "/Resource/images/silhouette.jpg";
    

    Or you could first create an image from the 'default image' and then you can use the return statement as before.