2

I have an enum with each value representing an image, for example:

public enum AnimalImages
{
    Cow,
    Cat,
    Dog
}

I also have a converter that takes the enum and returns an ImageSource:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    return ResourceManager.Instance.GetImageFromEnum((AnimalImages)value);
}

I am using WPF with MVVM; now, I want to add an image to my view. Using the Cow enum, I would like the cow image. I know that I can add a property to my ViewModel and call it like this:

public AnimalImages CowImage
{
   return AnimalImages.Cow;
}

and then bind it to my UI. But, I'm thinking there is a better way of doing this. Something like the following (which doesn't work of course):

<Image Source="{x:Static images:AnimalImages.Cow}, Converter={StaticResource AnimalImagesImageBitmapSource}}"/>

any suggestions?

Metro Smurf
  • 37,266
  • 20
  • 108
  • 140
Suave
  • 135
  • 1
  • 8
  • While the following S.O. answer isn't exactly what you're asking, it provides a couple of alternatives for using images with enums and WPF: http://stackoverflow.com/a/2534055/9664 – Metro Smurf Dec 25 '13 at 19:35

2 Answers2

2

Answer

That is the way to do it if the ViewModel property is an enum. It would look like this:

<!-- DataContext of the Image has to be the ViewModel -->
<Image Source="{Binding CowImage, Converter={StaticResource AnimalImagesImageBitmapSource}}"/>

Alternative

You could also do it so that your ViewModel property CowImage actually returns a URI or an ImageSource of the image, that way you don't need the converter and it looks "cleaner".

Like this:

ViewModel.cs

public ImageSource CowImage
{
    get 
    {
        return ResourceManager.Instance.GetImageFromEnum(AnimalImages.Cow);
    }
}

Xaml File

<Image Source="{Binding CowImage}"/>
Chris Leyva
  • 3,478
  • 1
  • 26
  • 47
0

You are almost there. Just need to use Binding and pass static value as Source.

<Image Source="{Binding Source={x:Static images:AnimalImages.Cow},
                    Converter={StaticResource AnimalImagesImageBitmapSource}}"/>
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185