Search code examples
c#wpfimagebindingstaticresource

Bind name of image resource


I have pictures in the windows resources:

<Window.Resources>
    <BitmapImage x:Key="Image1"  UriSource="../Resources/MyImages/Image1.png" />
    <BitmapImage x:Key="Image2"  UriSource="../Resources/MyImages/Image2.png" />
    <BitmapImage x:Key="Image3"  UriSource="../Resources/MyImages/Image3.png" />
</Window.Resources>

Their names match the names that I have in enum object in the model.

    private ImagesEnum _currentImage;
    public ImagesEnum CurrentImage
    {
        get { return _currentImage; }
        set
        {
            if (_currentImage!= value)
            {
                _currentImage= value;
                NotifyPropertyChanged("CurrentImage");
            }
        }
    }

the enum:

public enum ImagesEnum 
{
    Image1,
    Image2,
    Image3
}

I want to bind the name of the resource with the name that I have in the enum object.

Something like this:

<Image  Source="{StaticResource {Binding CurrentImage}}" />

Is there a way to do this?


Solution

  • Assuming that CurrentImage is of type ImagesEnum and represent the current image to show, you can use a value converter:

    public class ImagesEnumToSourceConverter: IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if(value is ImagesEnum imagesEnum)
            {
                switch(imagesEnum)
                {
                    case ImagesEnum.Image1:
                        return "../Resources/MyImages/Image1.png";
                    case ImagesEnum.Image2:
                        return "../Resources/MyImages/Image2.png";
                    case ImagesEnum.Image3:
                        return "../Resources/MyImages/Image3.png";
                }
            }
            return DependencyProperty.UnsetValue;
        }
    }
    

    Your binding should be:

    <Window.Resources>
        <conv:ImagesEnumToSourceConverter x:Key="ImagesEnumToSource" />
    </Window.Resources>
    
    .....
    
    <Image Source="{Binding CurrentImage, Converter={StaticResource ImagesEnumToSource}}" />