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

时间:2012-08-17 17:07:09

标签: .net xaml windows-runtime windows-store-apps winrt-xaml

在我的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, Type targetType, object parameter, 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()动态索引,以避免每次集合更改时不断更新索引值。

4 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:3)

我相信这里的代码示例很有用 https://msdn.microsoft.com/en-us/library/ms750769(v=vs.85).aspx

答案 2 :(得分:1)

从未试图像这样做样式,但如果:

将背景颜色绑定到某个属性,该属性将根据listview中当前项目的索引通过IValueConverter设置。

如果我有任何意义。

修改

有趣的是,在我写答案时,Filip Skakun的想法完全相同。

答案 3 :(得分:0)

我在网上搜索并找到了一项技术,其中包括向相关模型添加索引属性,然后将转换器添加到DataTemplate。这并不理想,因为它只更改了列表项的内容,因此根据填充和内容对齐,您会看到行背景周围的间隙。我也不喜欢用UI代码修改我的数据模型对象的代码味道。

试试这会有所帮助, http://www.bendewey.com/index.php/523/alternating-row-color-in-windows-store-listview