我遇到的问题是列表框绑定文本正在显示但没有绑定图像。我下载并解析一个xml文件就好了,然后显示我想要的文本,然后根据状态显示图像。 Linename
和Service
显示正常,但绑定图片根本不显示。 Atype只是用来调用GetImage方法(我不知道)。然后应该根据状态设置ImageSource,但根本不显示图像。
XElement XmlTweet = XElement.Parse(e.Result);
var ns = XmlTweet.GetDefaultNamespace();
listBox1.ItemsSource = from tweet in XmlTweet.Descendants(ns + "LineStatus")
select new FlickrData
{
Linename = tweet.Element(ns + "Line").Attribute("Name").Value,
Service = tweet.Element(ns + "Status").Attribute("Description").Value,
Atype = GetImage(tweet.Element(ns + "Status").Attribute("Description").Value)
};
public String GetImage(String type)
{
FlickrData f = new FlickrData();
switch(type)
{
case "Good Service":
f.Type = new BitmapImage(new Uri("/Images/status_good.png", UriKind.Relative));
break;
case "Minor Delays":
f.Type = new BitmapImage(new Uri("/Images/status_minor.png", UriKind.Relative));
break;
case "Severe Delays":
f.Type = new BitmapImage(new Uri("/Images/status_severe.png", UriKind.Relative));
break;
case "Planned Closure":
f.Type = new BitmapImage(new Uri("/Images/status_minor.png", UriKind.Relative));
break;
}
return "anything";
}
在FlickrData中,这是一个简单的get set,其中imagesource Type
没有显示。
public class FlickrData
{
public string Linename { get; set; }
public string Service { get; set; }
public string Detail { get; set; }
public ImageSource Type { get; set; }
public string Atype { get; set; }
}
答案 0 :(得分:1)
转换器在这种情况下会派上用场。
首先,XAML中的图像应该像这样定义
<Image Source="{Binding Path=Atype, Converter={StaticResource AtypeToImageConverter}}" Width="100" Height="100"/>
然后在项目中创建转换器类。 (右键单击项目名称 - &gt;选择添加 - >选择类)
将类命名为“AtypeToImageConverter”
public class AtypeToImageConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (targetType != typeof(ImageSource))
throw new InvalidOperationException("The target must be an ImageSource");
BitmapImage result = null;
int type = value.ToString();
switch (type)
{
case "Good Service":
result = new BitmapImage(new Uri("/Images/status_good.png", UriKind.Relative));
break;
case "Minor Delays":
result = new BitmapImage(new Uri("/Images/status_minor.png", UriKind.Relative));
break;
//other cases
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
它会发挥魔力。您可以从FlickrData类中删除Type。 有任何疑问,只需谷歌如何在C#中使用转换器