【发布时间】:2010-03-23 00:33:51
【问题描述】:
我有一个数据绑定列表框,它实际上显示了两列数据。显示如下:
<UserControl.Resources>
<DataTemplate x:Key="AlignedPairs">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="10" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Fruits}" Grid.Column="0" />
<TextBlock Text="->" TextAlignment="Center" Grid.Column="1" />
<TextBlock Text="{Binding Colors}" Grid.Column="3" />
</Grid>
</DataTemplate>
</UserControl.Resources>
<ListBox Name="lbStuff" Grid.ColumnSpan="2" Grid.Row="1"
ItemTemplate="{StaticResource AlignedPairs}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
然后在代码隐藏中设置Itemsource。
然而,基于一些逻辑,我想在其中一列中设置一行或一个项目,例如将水果变为红色,或将线条变为粗体。我有代码可以确定我想在后面的代码中区分哪种水果或颜色(通过颜色/粗体),但我无法弄清楚,特别是考虑到自定义列表框显示,我该如何设置特定项目换成不同的颜色/粗体。
有人有什么想法吗?
如果需要任何其他代码,请告诉我。干杯。
edit: 我真正想做的就是让问题尽可能简单...遍历列表框中的每个项目并检查字符串是否匹配在列表框/列表视图中以某种方式在视觉上区分此项目。没有必要让这变得比它需要的更复杂。为什么你不能单独设置项目的前景色超出我的理解!
编辑 2:
看起来我几乎通过以下方式到达那里(但它会引发异常并且不起作用)
foreach (var li in ListView.Items)
{
if (someCriteria == true)
{
((ListViewItem) li).Foreground = Brushes.Red;
//exception throw as this is the actual object stored in this location (the Fruit object for example) not the row or listviewitem I want to change the color of so it can't be cast :(
}
}
【问题讨论】:
-
您的数据是如何建模的——Fruits 是字符串、Fruit 对象还是集合?什么信息控制显示,例如您是否有要显示为粗体的 IsPrizeWinningFruit 属性,或者您需要基于名称,还是什么?
-
Fruit 和 Color 都是对象,例如,具有 Name 和 Code 属性。此屏幕显示两者之间的关系(水果和颜色)。共有三个文本文件fruit.txt、color.txt 和relationship.txt。应用程序具有三个屏幕 - 水果、颜色和关系。水果可以添加删除水果。颜色添加删除颜色。关系 - 可以将两者联系起来。试图在此屏幕上显示两件事 - 如果水果在关系中但从fruit.txt 中丢失,相反,如果水果在fruit.txt 但不在relationship.txt 中。我已经用另一个列表框展示了第二个示例。