C# 图像不是';绑定后在列表框中显示
我有一个问题,在列表框中显示绑定文本,但没有绑定图像。我下载并解析了一个xml文件,很好地显示了我想要的文本,但是我想根据状态显示一个图像<代码>行名和C# 图像不是';绑定后在列表框中显示,c#,xml,windows-phone-7,C#,Xml,Windows Phone 7,我有一个问题,在列表框中显示绑定文本,但没有绑定图像。我下载并解析了一个xml文件,很好地显示了我想要的文本,但是我想根据状态显示一个图像行名和服务显示正常,但绑定图像根本不显示。Atype只是用来调用GetImage方法(我知道它不太整洁)。然后,它应该根据状态设置ImageSource,但根本不显示图像 XElement XmlTweet = XElement.Parse(e.Result); var ns = XmlTweet.GetDefaultNamespace(); list
服务
显示正常,但绑定图像根本不显示。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中,它是一个简单的获取集,不显示imagesource类型
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; }
}
在这种情况下,转换器就派上了用场
首先,XAML中的图像应该这样定义
<Image Source="{Binding Path=Atype, Converter={StaticResource AtypeToImageConverter}}" Width="100" Height="100"/>
它会变魔术。您可以从FlickrData类中删除该类型。
如果有任何疑问,只需在谷歌上搜索如何在C#中使用转换器,您是如何在UI中设置绑定的?非常感谢您的帮助。让它工作起来。还应注意在XAML中添加以下内容xmlns:c=“clr namespace:Mynamespace”
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();
}
}