WPF开发中遇到的问题及解决系列(三):如何改变ListView 中各行的背景色(背景色产生交替效果)
方法 1:定义使用 IValueConverter 来使背景色产生交替效果的样式
下面的示例显示如何为将 Background 属性的值绑定到 IValueConverter 的 ListViewItem 控件定义 Style。
<Style x:Key="myItemStyle" TargetType="{x:Type ListViewItem}">
<Setter Property="Background">
<Setter.Value>
<Binding RelativeSource="{RelativeSource Self}"
Converter="{StaticResource myConverter}"/>
</Setter.Value>
</Setter>
</Style>
<Setter Property="Background">
<Setter.Value>
<Binding RelativeSource="{RelativeSource Self}"
Converter="{StaticResource myConverter}"/>
</Setter.Value>
</Setter>
</Style>
下面的示例为 IValueConverter 定义 ResourceKey。下面的示例为 IValueConverter 定义 ResourceKey。
<namespc:BackgroundConverter x:Key="myConverter"/>
下面的示例显示依据行索引设置 Background 属性的 IValueConverter 的定义。下面的示例显示依据行索引设置 Background 属性的 IValueConverter 的定义。
public sealed class BackgroundConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture)
{
ListViewItem item = (ListViewItem)value;
ListView listView =
ItemsControl.ItemsControlFromItemContainer(item) as ListView;
// Get the index of a ListViewItem
int index =
listView.ItemContainerGenerator.IndexFromContainer(item);
if (index % 2 == 0)
{
return Brushes.LightBlue;
}
else
{
return Brushes.Beige;
}
}
{
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture)
{
ListViewItem item = (ListViewItem)value;
ListView listView =
ItemsControl.ItemsControlFromItemContainer(item) as ListView;
// Get the index of a ListViewItem
int index =
listView.ItemContainerGenerator.IndexFromContainer(item);
if (index % 2 == 0)
{
return Brushes.LightBlue;
}
else
{
return Brushes.Beige;
}
}
下面的示例演示如何定义使用 Style 作为其 ItemContainerStyle 以便提供所需布局的 ListView。下面的示例演示如何定义使用 Style 作为其 ItemContainerStyle 以便提供所需布局的 ListView。
<ListView Name="theListView"
ItemsSource="{Binding Source={StaticResource EmployeeData},
XPath=Employee}"
ItemContainerStyle="{StaticResource myItemStyle}" >
<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"/>
</GridView>
</ListView.View>
</ListView>
ItemsSource="{Binding Source={StaticResource EmployeeData},
XPath=Employee}"
ItemContainerStyle="{StaticResource myItemStyle}" >
<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"/>
</GridView>
</ListView.View>
</ListView>
另2种方法详见msdn:http://msdn2.microsoft.com/zh-cn/library/ms750769.aspx