Jason94
Jason94

Reputation: 13610

How can I bind an image source based on its name (string)?

Im creating an app that shows a rss that has several types of messages (alert, warning1, warning2). All of the types has a png (same as the message). They are all placed in the Images folder in my project.

So in my application I bind to a list of newsobjects. The newsobject has the string Type (alert, warning1, warning2).

But how can I bind the source of a image to the correct image based on this Type property?

Upvotes: 0

Views: 68

Answers (2)

Vladimir Gondarev
Vladimir Gondarev

Reputation: 1243

You have to use IValueConverter:

For Instance:

public class ImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var imagePath = (string) value;

            switch (imagePath)
            {
                case "warning":
                    return "/Images/warning.png";
                case "error":
                    return "/Images/error.png";
                default:
                    throw new InvalidOperationException();
            }
        }       
    }

then in xaml:

<UserControl.Resources>
        <converters:ImageConverter x:Key="imageConverter"/>

....

and finaly:

<Image Source="{Binding DataItem.Type,Converter={StaticResource imageConverter}}" />

Upvotes: 1

MGorgon
MGorgon

Reputation: 2597

In constructor of this newsObject class add switch(Type) block, and there apply different images according of Type value (I assume that in this class you have image or path_to_image atribute)

Upvotes: 1

Related Questions