[英]How can I bind an image source based on its name (string)?
我正在创建一个应用程序,显示一个rss,它有几种类型的消息(alert,warning1,warning2)。 所有类型都有一个png(与消息相同)。 它们都放在我项目的Images文件夹中。
所以在我的应用程序中,我绑定到newsobjects列表。 newsobject具有字符串Type
(alert,warning1,warning2)。
但是如何根据此Type属性将图像源绑定到正确的图像?
在这个newsObject类的构造函数中添加switch(Type)
块,并根据Type
值应用不同的图像(我假设在这个类中你有image或path_to_image属性)
你必须使用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}}" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.