更改Windows Phone 7中列表框项的颜色

时间:2012-06-20 21:19:01

标签: c# silverlight windows-phone-7 xaml

我有一个Windows Phone 7应用程序的列表框,显示从XML提要解析的信息。 我希望能够更改列表框中字体的颜色,具体取决于从XML源解析的值。我搜索过,找不到我想要的东西。这是我的代码:

foreach (var item in doc.Descendants("station"))
{
    if (item.Element("name").Value == dest)
    {
     listBox1.Items.Add(item.Element("name").Value);
     listBox1.Items.Add("Last Updated:");
     listBox1.Items.Add(item.Element("date").Value);
     listBox1.Items.Add(item.Element("time").Value);

         foreach (var item1 in item.Descendants("eta"))
         {
          listBox1.Items.Add(item1.Element("destination").Value);
          listBox1.Items.Add(item1.Element("estimate").Value);
         }//foreach

    }//if
}//outer foreach

我想要的是,例如,

if item.Element("name").Value="Fremont" and item1.Element("destination").Value="Daly City", 
then listBox1.Items.Add(item1.Element("destination").Value);
例如,

将显示绿色文本(对于“name”和“destination”的不同值,依此类推)。我发现的大多数例子都是WPF或WP7之外的其他东西。

2 个答案:

答案 0 :(得分:1)

最简单的方法基于您已有的,可能是将ListBoxItem个对象添加到列表框而不仅仅是字符串值。

然后你可以设置ListBoxItem.Foreground和其他属性。

// psuedocode, but reasonably close?
var lbi = new ListBoxItem { Content = item.Element("name").Value };
if (yourcondition)
    lbi.Foreground = new SolidColorBrush(Colors.Green);
listBox1.Items.Add(lbi);

虽然这确实有效,但McAden的回答是理想上更正确,因为你应该真正考虑使用DataBinding和模板和东西,而不是在代码/代码隐藏中完成所有这些工作。它们将来会让你的生活更加轻松

答案 1 :(得分:1)

这个答案使用的是DataBinding,它看起来并不像你正在使用的那样,但你可以将doc.Descendants("station")公开为属性并将列表框绑定到它。然后,为列表框项定义DataTemplate以显示要显示的字段的哪个部分。对于颜色,您可以将Foreground绑定到项目并定义转换器以转换项目以返回它应该是什么颜色。