Donate

WPF DataGrid Set RowBackground Using AlternationCount And DataTriggers

Hi,
There was a question raised on how to set the WPF DataGrid RowBackground with AlternationCount (alternating row colors) and DataTriggers without overriding the Alternation count. The fix is to declare a DataGrid.Style that contains settings for RowBackGround and AlternationCount. And in your DataGrid.RowStyle, define the DataTriggers to highlight RowBackground based on a given Value.
<DataGrid x:Name="dgEmployees" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Top" Height="346" 
                  RowHeaderWidth="0" AutoGenerateColumns="False" CanUserAddRows="False" CanUserResizeColumns="False" 
                  CanUserDeleteRows="False" ScrollViewer.CanContentScroll="True" VerticalScrollBarVisibility="Visible" 
                  HeadersVisibility="Column" IsReadOnly="True" >
 <DataGrid.Resources>
  <SolidColorBrush x:Key="ConrolLightColorKey" Color="{DynamicResource {x:Static SystemColors.ControlLightColorKey}}"/>
 </DataGrid.Resources>
 <DataGrid.Style>                
  <Style TargetType="{x:Type DataGrid}">
   <Setter Property="RowBackground" Value="{StaticResource ConrolLightColorKey}"/>
   <Setter Property="AlternationCount" Value="2" />
  </Style>
 </DataGrid.Style>
 <DataGrid.RowStyle>
  <Style TargetType="DataGridRow">
   <Style.Triggers>
    <DataTrigger  Binding="{Binding Department}" Value="1">
     <Setter Property="Background" Value="Red"></Setter>
    </DataTrigger>
    <DataTrigger Binding="{Binding Department}" Value="2">
     <Setter Property="Background" Value="Green"></Setter>
    </DataTrigger>
   </Style.Triggers>
  </Style>
 </DataGrid.RowStyle>
 <DataGrid.Columns>
  <DataGridTextColumn Header="ID" Binding="{Binding ID}" Width="50*" />
  <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" Width="120*" />
  <DataGridTextColumn Header="Last Name" Binding="{Binding LastName}" Width="120*" />
  <DataGridTextColumn Header="Department" Binding="{Binding Department}" Width="120*" />
 </DataGrid.Columns>
</DataGrid>

Cheers!

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.