日期:2014-05-20  浏览次数:20958 次

改变 ListView 中各行的背景色
后台代码:
public class ListViewItemStyleSelector : StyleSelector
{
    public override Style SelectStyle(object item, 
        DependencyObject container)
    {
        Style st = new Style();
        st.TargetType = typeof(ListViewItem);
        Setter backGroundSetter = new Setter();
        backGroundSetter.Property = ListViewItem.BackgroundProperty;
        ListView listView = 
            ItemsControl.ItemsControlFromItemContainer(container) 
              as ListView;
        int index = 
            listView.ItemContainerGenerator.IndexFromContainer(container);
        if (index % 2 == 0)
        {
            backGroundSetter.Value = Brushes.LightBlue;
        }
        else
        {
            backGroundSetter.Value = Brushes.Beige;
        }
        st.Setters.Add(backGroundSetter);
        return st;
    }
}    


下面的示例演示如何为 StyleSelector 定义 ResourceKey。namespc 前缀映射到 CLR 命名空间和其中定义了 StyleSelector 的对应程序集。有关更多信息,请参见 XAML 命名空间和命名空间映射。

<namespc:ListViewItemStyleSelector x:Key="myStyleSelector"/>

下面的示例演示如何将 ListView 的 ItemContainerStyleSelector 属性设置为此 StyleSelector 资源。


<ListView 
      ItemsSource="{Binding Source={StaticResource EmployeeData}, 
                                        XPath=Employee}"
      ItemContainerStyleSelector="{DynamicResource myStyleSelector}" >      
  <ListView.View>
    <GridView>
      <GridViewColumn DisplayMemberBinding="{Binding XPath=FirstName}" 
                      Header="First Name" Width="120"/>
      <GridViewColumn DisplayMemberBinding="{Binding XPath=LastName}" 
                      Header="Last Name" Width="120"/>
      <GridViewColumn DisplayMemberBinding="{Binding XPath=FavoriteCity}" 
                      Header="Favorite City" Width="120"/>