[英]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). 我正在创建一个应用程序,显示一个rss,它有几种类型的消息(alert,warning1,warning2)。 All of the types has a png (same as the message).
所有类型都有一个png(与消息相同)。 They are all placed in the Images folder in my project.
它们都放在我项目的Images文件夹中。
So in my application I bind to a list of newsobjects. 所以在我的应用程序中,我绑定到newsobjects列表。 The newsobject has the string
Type
(alert, warning1, warning2). newsobject具有字符串
Type
(alert,warning1,warning2)。
But how can I bind the source of a image to the correct image based on this Type property? 但是如何根据此Type属性将图像源绑定到正确的图像?
在这个newsObject类的构造函数中添加switch(Type)
块,并根据Type
值应用不同的图像(我假设在这个类中你有image或path_to_image属性)
You have to use IValueConverter: 你必须使用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: 然后在xaml:
<UserControl.Resources>
<converters:ImageConverter x:Key="imageConverter"/>
.... ....
and finaly: 最后:
<Image Source="{Binding DataItem.Type,Converter={StaticResource imageConverter}}" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.