如何根据图像源的名称(字符串)绑定图像源

本文关键字:图像 字符串 绑定 何根 | 更新日期: 2023-09-27 18:24:41

我正在创建一个应用程序,该应用程序显示具有多种类型消息(alert、warning1、warning2)的rss。所有类型都有一个png(与消息相同)。它们都放在我项目的Images文件夹中。

因此,在我的应用程序中,我绑定到一个新闻对象列表。newsobject具有字符串Type(alert、warning1、warning2)。

但是,如何基于此Type属性将图像的源绑定到正确的图像?

如何根据图像源的名称(字符串)绑定图像源

您必须使用IValueConverter:

例如:

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();
            }
        }       
    }

然后在xaml:中

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

最后:

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

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