我如何根据列表视图项目在wpf中的HarfNotu值更改ListView项目背景颜色

时间:2013-04-20 23:40:18

标签: wpf listviewitem

我的ListView看起来像: http://oi36.tinypic.com/ek5n3o.jpg

我的listview xaml:

<ListView  Name="notListView" Width="550" HorizontalAlignment="Left">
        <ListView.View>
        <GridView AllowsColumnReorder="true">
            <GridViewColumn Header="Ders Kodu" Width="100" DisplayMemberBinding="{Binding Path=DersKodu}" />
            <GridViewColumn Header="Ders Adı" Width="200" DisplayMemberBinding="{Binding Path=DersAdi}" />
            <GridViewColumn Header="Vize" Width="50" DisplayMemberBinding="{Binding Path=Vize}" />
            <GridViewColumn Header="Final" Width="50" DisplayMemberBinding="{Binding Path=Final}" />
            <GridViewColumn Header="Ortalama" Width="60" DisplayMemberBinding="{Binding Path=Ortalama}" />
            <GridViewColumn Header="Harf Notu" Width="60" DisplayMemberBinding="{Binding Path=Harf}" />
        </GridView>
    </ListView.View>
</ListView>

我的.cs代码:

notListView.ItemsSource = notGoruntule(1, 1); // notGoruntule() function returns an Arraylist, which contains my "Notlar" objects.

我试过了:

ListViewItem lvitem = (ListViewItem)notListView.Items[0];
lvitem.Background = Brushes.Red;

但是第一线抛出:

Unable to cast object of type 'OBS_Interface_5.Classes.Notlar' to type 'System.Windows.Controls.ListViewItem'.

我如何解决这个问题?

1 个答案:

答案 0 :(得分:70)

您可以{x}直接Style xaml中的ListViewItem

示例:

假设您的“Harf”变量是一个字符串,您可以尝试

<ListView Name="notListView"
          Width="550"
          HorizontalAlignment="Left">
  <ListView.Resources>
    <Style TargetType="{x:Type ListViewItem}">
      <Style.Triggers>
        <DataTrigger Binding="{Binding Harf}"
                      Value="1">
          <Setter Property="Background"
                  Value="Red" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </ListView.Resources>
  ...

现在任何“Harf”值为1的ListView行都会有一个“红色”Background