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

Car*_*s P 8 .net xaml windows-runtime winrt-xaml windows-store-apps

在我的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>
Run Code Online (Sandbox Code Playgroud)

在WPF中,这是使用带触发器的样式完成的 - 请参阅此页面.

你如何在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, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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

myCollection.add(item);
item.IndexWithinParentCollection = myCollection.Count;
Run Code Online (Sandbox Code Playgroud)

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

Fil*_*kun 5

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

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