Monday, October 24, 2016

Set WPF DataGridCell and DataGridRow color using Triggers

Hi,

There was a question on the forums on how to set the color of DataGridCell or DataGridRow using XAML without code. I always thought that the solution will be to use code using IValueConverter. After doing some searching on MSDN and google, the answer is straightforward using Triggers. To set the color of DataGridRow, you set the DataGrid.CellStyle just below the DataGrid markup.
<DataGrid Grid.Row="0" Grid.Column="0" AutoGenerateColumns="False" CanUserAddRows="False"  Name="dgStudents">
 <DataGrid.CellStyle>
  <Style TargetType="{x:Type DataGridCell}">
   <Style.Triggers>
    <DataTrigger Binding="{Binding Age}" Value="28">
     <Setter Property="Background" Value="Gray"></Setter>
    </DataTrigger>
   </Style.Triggers>
  </Style>
 </DataGrid.CellStyle>
 <DataGrid.Columns>               
  <DataGridTextColumn Header="ID" Binding="{Binding Path=ID}" Width="120" IsReadOnly="True" />
  <DataGridTextColumn Header="Age" Binding="{Binding Path=Age}" MinWidth="100" IsReadOnly="True" />
  <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" MinWidth="150" IsReadOnly="True" />
  <DataGridTextColumn Header="Address" Binding="{Binding Path=Address}" MinWidth="150" IsReadOnly="True" />
 </DataGrid.Columns>
</DataGrid>
To set the DataGridCell color, you need to apply the Style of a specific column such as DataGridTextColumn.
<DataGrid Grid.Row="0" Grid.Column="0" AutoGenerateColumns="False" CanUserAddRows="False"  Name="dgStudents">
 <DataGrid.Columns>               
  <DataGridTextColumn Header="ID" Binding="{Binding Path=ID}" Width="120" IsReadOnly="True" />
  <DataGridTextColumn Header="Age" Binding="{Binding Path=Age}" MinWidth="100" IsReadOnly="True">
   <DataGridTextColumn.CellStyle>
    <Style TargetType="DataGridCell">
     <Style.Triggers>
      <DataTrigger Binding="{Binding Path=Age}" Value="28">
       <Setter Property="Background" Value="Gray"/>
      </DataTrigger>
     </Style.Triggers>
    </Style>
   </DataGridTextColumn.CellStyle>
  </DataGridTextColumn>
  <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" MinWidth="150" IsReadOnly="True" />
  <DataGridTextColumn Header="Address" Binding="{Binding Path=Address}" MinWidth="150" IsReadOnly="True" />
 </DataGrid.Columns>
</DataGrid>
Note: Both markups will set the color of the row and cell based from the value of Age which is 28.

0 comments:

Post a Comment