列表视图的备用行颜色 - uwp

时间:2017-12-14 08:07:32

标签: c# xaml uwp

如何为listview设置备用行颜色?我将每个项目设置为datatemplate。将值绑定到textblock。因此无法通过listview项目进行迭代。我如何实现它?

 <ListView x:Name="list1"  Width="300" Height="500" Background="White"  Loaded="list1_Loaded"   Style="{StaticResource FixedHeaderListViewStyle}">
            <ListView.ItemTemplate>
                <DataTemplate >
                    <Grid Tapped="StackPanel_Tapped" Width="300" Height="38">                    
                    <Border  Width="390" Height="38"  HorizontalAlignment="Stretch">
                    <TextBlock  Text="{Binding ItemUserName}" Padding="4" TextWrapping="Wrap"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" TextAlignment="Left" Foreground="White"/>
                    </Border>
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

  private void list1_Loaded(object sender, RoutedEventArgs e)
    {  
        ListView listView = sender as ListView;
        ItemCollection ic = listView.Items;
        int counter = 1;
        foreach (ListViewItem item in ic)
        {
            if (counter % 2 == 0)
            {
                item.Background = new SolidColorBrush(Colors.Orange);
                item.Foreground = new SolidColorBrush(Colors.DarkRed);
            }
            else
            {
                item.Background = new SolidColorBrush(Colors.OrangeRed);
                item.Foreground = new SolidColorBrush(Colors.Snow);
            }
            counter++;
        }

    }

2 个答案:

答案 0 :(得分:1)

得到如下解决方案

void BackgroundAlternatingListView_ContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args)
{
    if (args.ItemIndex % 2 != 0)
    {
        args.ItemContainer.Background = new SolidColorBrush(_secondColor);
    }
    else
    {
        args.ItemContainer.Background = new SolidColorBrush(_startColor);
    }
}

答案 1 :(得分:0)

只需使用<AlternatingItemTemplate>并为其设置不同的颜色,控制器上不需要任何代码。