C# 更改Windows Phone 7中列表框项目的颜色
我有一个WindowsPhone7应用程序的列表框,显示从XML提要解析的信息。 我希望能够根据从XML提要解析的值更改列表框中字体的颜色。我已经找过了,找不到我要找的东西。以下是我的代码:C# 更改Windows Phone 7中列表框项目的颜色,c#,silverlight,windows-phone-7,xaml,C#,Silverlight,Windows Phone 7,Xaml,我有一个WindowsPhone7应用程序的列表框,显示从XML提要解析的信息。 我希望能够根据从XML提要解析的值更改列表框中字体的颜色。我已经找过了,找不到我要找的东西。以下是我的代码: foreach (var item in doc.Descendants("station")) { if (item.Element("name").Value == dest) { listBox1.Items.Add(item.Element("name").Value);
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以外的其他对象的 根据您已有的内容,最简单的方法可能是将ListBoxItem
对象添加到listbox,而不仅仅是字符串值
然后您可以设置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的答案在理想情况下更为正确,因为您应该真正研究使用数据绑定、模板和其他东西,而不是在代码/代码隐藏中完成所有这些工作。他们会让你的生活在未来变得更轻松 这个答案使用的是数据绑定,它看起来不像您正在使用的,但是您可以将
doc.subjections(“station”)
作为属性公开,并将列表框绑定到它。然后,为listbox项定义DataTemplate,以显示要显示的字段部分。对于颜色,您可以将前景
绑定到该项,并定义一个转换器来转换该项,以返回其应为的颜色。画笔。绿色变为红色,表示当前上下文中不存在画笔?遵循此回答的逻辑:lbi.Foreground=new SolidColorBrush(Colors.Green);Amanda_Panda你住在达拉斯地区吗?我同意这是一种更正确的方式,所以我会投你的票,尽管我的标为正确。在这种情况下,提出我的建议比建议学习数据绑定更容易:)