WPF DataGrid columns alternate coloring

How can I create column coloring in a DataGrid if I also want to use the AlternatingRowBackground property? I have some ideas, but this does not work: (.

<de:DataGrid Name="dataGrid1"
                             AlternationCount="2"
                             AlternatingRowBackground="Salmon"
                             >
                    <de:DataGrid.Columns>
                        <de:DataGridTextColumn Binding="{Binding Path=Phrase}"
                                               Header="Phrase">
                            <de:DataGridTextColumn.ElementStyle>
                                <Style TargetType="{x:Type TextBlock}">
                                    <Style.Triggers>
                                        <Trigger Property="ItemsControl.AlternationIndex" Value="0">
                                            <Setter Property="Background" Value="Green"></Setter>
                                        </Trigger>
                                        <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                                            <Setter Property="Background" Value="Red"></Setter>
                                        </Trigger>

                                    </Style.Triggers>
                                </Style>
                            </de:DataGridTextColumn.ElementStyle>
                        </de:DataGridTextColumn>
                     </de:DataGrid.Columns>
                </de:DataGrid>

Maybe someone knows a working solution? Thank.

+3
source share
1 answer

You are looking for the AlternationIndex property in the wrong control. This property belongs to DataGridRow.

<DataGrid ItemsSource="{Binding}" AlternationCount="2" AutoGenerateColumns="False" AlternatingRowBackground="Salmon">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Path=Phrase}" Header="Phrase">
                    <DataGridTextColumn.ElementStyle>
                        <Style TargetType="{x:Type TextBlock}">
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding AlternationIndex, RelativeSource={RelativeSource AncestorType=DataGridRow}}" Value="0">
                                    <Setter Property="Background" Value="Green"></Setter>
                                </DataTrigger>
                                <DataTrigger Binding="{Binding AlternationIndex, RelativeSource={RelativeSource AncestorType=DataGridRow}}" Value="1">
                                    <Setter Property="Background" Value="Red"></Setter>
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </DataGridTextColumn.ElementStyle>
                </DataGridTextColumn>
            </DataGrid.Columns>
          </DataGrid>
0
source

Source: https://habr.com/ru/post/1771179/


All Articles