0

我有一个问题,在列表框中显示绑定文本但没有绑定图像。我很好地下载并解析了一个 xml 文件并显示我想要的文本,但随后想根据状态显示图像。LinenameService显示 OK 但绑定图像根本不显示。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 中,这是一个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; }

    }
4

1 回答 1

1

在这种情况下,转换器就派上用场了。

首先,您在 XAML 中的图像应该这样定义

<Image Source="{Binding Path=Atype, Converter={StaticResource AtypeToImageConverter}}" Width="100" Height="100"/>

然后在项目中创建一个转换器类。(右键单击项目名称 -> 选择 Add -> 选择 Class )

将类命名为“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 类中删除类型。有任何疑问,只是谷歌如何在 C# 中使用转换器

于 2013-03-21T13:51:52.100 回答