我有一个类,通过传递一个对象列表填充ListView.该类使用反射来查看每个对象的属性,以便生成ListView.如何更改ListView中行的背景颜色.
这个页面完全符合我的要求.唯一的问题是我的ListView绑定到对象列表.换句话说,ListView的每个项都是绑定的对象而不是ListViewItem.我假设这就是我无法将ListView中的某些项目转换为ListViewItem的原因.例如,当我这样做时:
ListViewItem someItem = (ListViewItem)listView1.Items[0];
我得到一个InvalidcastException,因为如果我将对象物理添加到ListView,如:
listview.items.add(someObject)然后这将工作,但因为我将列表绑定到ListView该行不起作用.我认为这就是我无法施展的原因.我想要转换它的原因是因为ListViewItem具有Background属性.
编辑
我能够用我尝试过的前12个对象来做到这一点:
for (int i = 0; i < listView1.Items.Count; i++)
{
    var lvitem = listView1.ItemContainerGenerator.ContainerFromIndex(i) as ListViewItem;
    lvitem.Foreground = Brushes.Green;                
}
我收到此错误:

我也试过这个:
foreach (Tiro t in listView1.Items)
{
    var lvitem = listView1.ItemContainerGenerator.ContainerFromItem(t) as ListViewItem;
    if (t.numero == 0 || t.numero == 37)
    {
        //lvitem.Background = Brushes.Green;
        lvitem.Foreground = Brushes.Green;
    }
    else if (t.numero % 2 == 0)
    {
        //lvitem.Background = Brushes.Red;
        lvitem.Foreground = Brushes.Red;
    }
    else
    {
        //lvitem.Background = Brushes.Gray;
        lvitem.Foreground = Brushes.Black;
    }
}
我得到同样的错误:

我不明白为什么lvitem在12次迭代后为空?
它只适用于正在显示的项目....
Gis*_*shu 10
您需要引入ViewModels而不是粉碎WPF UI.例如,我可以创建一个如下
public class ItemVM : INotifyPropertyChanged // if you want runtime changes to be reflected in the UI
{
  public string Text {... raise property change in setter }
  public Color BackgroundColor {... ditto... }
}
接下来,在DataContext中创建一个这样的对象列表作为属性,以便ListView可以绑定到它.
// e.g. MainWindow
    public IEnumerable<ItemVM> Items { get; set; }
现在您需要做的就是将ListView绑定到此集合,并正确连接UI的DataContext
       <ListView x:Name="MyListView" ItemsSource="{Binding Items}" HorizontalContentAlignment="Stretch">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Text}">
                    <TextBlock.Background>
                        <SolidColorBrush Color="{Binding BackgroundColor}"/>
                    </TextBlock.Background>
                    </TextBlock>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <Button Click="Button_Click" Content="Go PaleGreen"/>
现在改变背景颜色很容易.只需将相应ItemVM对象的属性设置为所需的颜色即可.例如,将所有项目设置为PaleGreen
private void Button_Click(object sender, RoutedEventArgs e)
    {
        foreach (var item in Items)
            item.BackgroundColor = Colors.PaleGreen;
    }
使用时ItemContainerGenerator请注意容器是异步生成的。生成器公开了一个您可以监听的状态更改事件:
listView.ItemContainerGenerator.StatusChanged += new EventHandler(ContainerStatusChanged);     
private void ContainerStatusChanged(object sender, EventArgs e)  
{  
    if (listView.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)  
    {  
        foreach (Tiro t in listView1.Items)
        {
            ...
        }
    }  
}
不确定这是否会产生任何奇怪的绘图效果(闪烁)。
另一种选择是使用数据模板,而不是在代码中构建列表视图项。不过,出于显示目的,您可能必须向视图模型添加一些属性。