wpf datagrid row background color alternatively changed based on row index,AlternationConverter,AlternationCount

<Window x:Class="WpfApp7.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp7"
        mc:Ignorable="d" WindowState="Maximized" WindowStartupLocation="CenterOwner"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.Resources>
            <AlternationConverter x:Key="rowBgColor">
                <SolidColorBrush>Red</SolidColorBrush>
                <SolidColorBrush>Blue</SolidColorBrush>
                <SolidColorBrush>Green</SolidColorBrush>
                <SolidColorBrush>Orange</SolidColorBrush>
            </AlternationConverter>
            <Style x:Key="dgRowStyle" TargetType="{x:Type DataGridRow}">
                <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource self},
                    Path=(ItemsControl.AlternationIndex),Converter={StaticResource rowBgColor }}"></Setter>
            </Style>
        </Grid.Resources>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="50"/>
        </Grid.RowDefinitions>
        <DataGrid x:Name="mainDG" Grid.Row="0" VirtualizingPanel.IsContainerVirtualizable="True" VirtualizingPanel.IsVirtualizing="True"
                      EnableColumnVirtualization="True" EnableRowVirtualization="True" 
                      VirtualizingPanel.IsVirtualizingWhenGrouping="True" VirtualizingPanel.VirtualizationMode="Recycling"
                    AlternationCount="4"  RowStyle="{StaticResource dgRowStyle}" >            
        </DataGrid>
        <Button Content="Load Data" Click="Button_Click" Grid.Row="1"/>
    </Grid>
</Window>

 

 

posted @ 2024-03-12 17:13  FredGrit  阅读(5)  评论(0编辑  收藏  举报