Reputation: 135
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?
Upvotes: 2
Views: 115
Reputation: 81253
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}}"/>
Upvotes: 0
Reputation: 3526
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}}"/>
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}"/>
Upvotes: 2