.net – Metro应用程序 – ListView – 如何替换ListViewItems的背景颜色

在我的Windows 8 Metro风格应用程序中,我将Listview绑定到ObservableCollection,我希望每个ListViewItem的背景颜色交替(白色,灰色,白色等)
<ListView x:Name="stopsListView" ItemsSource="{Binding}" >
        <ListView.ItemTemplate>
            <DataTemplate>
                <Grid Height="66" >
                    <TextBlock Text="{Binding Title}" />
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>

在WPF中,这是使用带触发器的样式完成的 – 请参阅this page.

你如何在Metro应用程序中实现这一目标?

更新:

在下面给出了正确的答案后,我离开并实际编码了它.以下是需要它的人的一些代码

值转换器类代码

public class AltBackgroundConverter : IValueConverter
{
    public object Convert(object value,Type targettype,object parameter,string language)
    {
        if (!(value is int)) return null;
        int index = (int)value;

        if (index % 2 == 0)
            return Colors.White;
        else
            return Colors.LightGray;
    }

    // No need to implement converting back on a one-way binding
    public object ConvertBack(object value,string language)
    {
        throw new NotImplementedException();
    }
}

XAML列表视图的代码



<ListView x:Name="stopsListView" ItemsSource="{Binding}">

        <ListView.ItemTemplate>
            <DataTemplate>
                <Grid Width="250" Height="66" Margin="5">
                    <Grid.Background>
                        <SolidColorBrush Color="{Binding IndexWithinParentCollection,Mode=OneWay,Converter={StaticResource AltBGConverter}}" />
                    </Grid.Background>

…并且,在向集合中添加项目或修改集合时,请记住在集合中设置其索引:

myCollection.add(item);
item.IndexWithinParentCollection = myCollection.Count;

当然,如果您的集合经常更改,这种方法维护成本很高,因为您必须重新索引您的项目,因此我发现在每个项目中存储对父集合的引用更容易,然后计算索引使用.IndexOf()飞行以避免每次集合更改时不断更新索引值.

您可以使用转换器 – 从项目中获取行索引并将其转换为画笔.另外 – 如果ItemTemplate没有给你足够的控制 – 使用ItemContainerStyle修改ListViewItem模板级别的画笔.

一个选项可能是指定一个ItemTemplateSelector,它根据项目为您提供具有不同画笔的不同模板.您仍然需要生成行索引,或者以某种方式启用选择器以确定项目是处于偶数位置还是奇数位置.

相关文章

Windows注册表操作基础代码 Windows下对注册表进行操作使用的...
黑客常用WinAPI函数整理之前的博客写了很多关于Windows编程的...
一个简单的Windows Socket可复用框架说起网络编程,无非是建...
Windows文件操作基础代码 Windows下对文件进行操作使用的一段...
Winpcap基础代码 使用Winpcap进行网络数据的截获和发送都需要...
使用vbs脚本进行批量编码转换 最近需要使用SourceInsight查看...