Search code examples
wpfc#-4.0bindingivalueconverterimagesource

Changing a Image Source at runtime does not display the image


I am trying to display an Image within a ListBox.ItemTemplate depending on its binding value, the binding value is the status of an object (pending, retrieved, posted, complete or errored), here is the XAML for the Image element.

<Window.Resources>
    <local:StatusImageConverter x:Key="StatusImage" />
</Window.Resources>

<Image Source="{Binding Path=Status, Converter={StaticResource StatusImage}}" />

I have added 2 images (Badge_tick, Badge_cross) to the Project resource and use the IValueConverter interface to convert the status to an Image which will be displayed in the template, here is the Converter class

[ValueConversion(typeof(PreTripItem.PreTripItemStatus), typeof(Bitmap))]
public class StatusImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        PreTripItem.PreTripItemStatus status = (PreTripItem.PreTripItemStatus)value;

        switch (status)
        {
            case PreTripItem.PreTripItemStatus.Complete:
                return new Bitmap(Properties.Resources.Badge_tick);
            case PreTripItem.PreTripItemStatus.Error:
                return new Bitmap(Properties.Resources.Badge_cross);
            default:
                return null;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();  //Does not need to be converted back
    }
}

This builds/compiles fine and runs but when the status changes the image is not displayed within the TemplateItem. I am using the INotifyPropertyChanged interface within my classes so the interface knows when the property is changed automatically so I know straight away that is not the problem :)

I have trawled through the university of google and seen lot of posts with the same problem in principle but not come accross a solution when using the converter interface and project resources.

Can anyone help? Thanks in advance

All my other IValueConverter classes are working perfectly, just not this one.


Solution

  • Try returning a BitmapSource type inplace of Bitmap

    Bits to change:

    [ValueConversion(typeof(PreTripItem.PreTripItemStatus), typeof(BitmapSource))] 
    

    and return a BitmapImage as in:

    return new BitmapImage(new Uri("pack://application:,,,/Resources/Image1.png"));