Search code examples
c#wpfwpfdatagrid

How do I Prevent alternatingRowBackground for particular columns in DataGrid WPF?


I mean, I don't want alternatingRowBackground for rows in few columns

<DataGrid
    AutoGenerateColumns="False" AlternatingRowBackground="LightBlue" AlternationCount="2"
    CanUserResizeRows="False" CanUserResizeColumns="False" CanUserAddRows="false"
    CanUserDeleteRows="false" CanUserReorderColumns="false" CanUserSortColumns="false"
    FontSize="15" FontWeight="SemiBold" ItemsSource="{Binding Collection}"
    SelectedIndex="{Binding SelectedRowIndex, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
    Grid.ColumnSpan="2" RowHeaderWidth="0"
>

Solution

  • You can use CellStyle property to set different style for cells within a particular column.

    <DataGrid AutoGenerateColumns="False" AlternatingRowBackground="LightBlue" AlternationCount="2"
            CanUserResizeRows="False" CanUserResizeColumns="False" CanUserAddRows="false"
            CanUserDeleteRows="false" CanUserReorderColumns="false" CanUserSortColumns="false"
            FontSize="15" FontWeight="SemiBold" ItemsSource="{Binding Collection}"
            SelectedIndex="{Binding SelectedRowIndex, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
            Grid.ColumnSpan="2" RowHeaderWidth="0">
        <DataGrid.Resources>
            <Style TargetType="DataGridCell" x:Key="WhiteBackgroundCell">
                <Setter Property="Background" Value="White" />
            </Style>
        </DataGrid.Resources>
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Prop1}" Header="Prop1" CellStyle="{StaticResource WhiteBackgroundCell}" />
            <DataGridTextColumn Binding="{Binding Prop2}" Header="Prop2" />
        </DataGrid.Columns>
    </DataGrid>