简体   繁体   中英

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?

在这个newsObject类的构造函数中添加switch(Type)块,并根据Type值应用不同的图像(我假设在这个类中你有image或path_to_image属性)

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}}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM