Wojciech Szabowicz
Wojciech Szabowicz

Reputation: 4198

WPF styling cells in one column in data grid

I have a question I have a table with 4 columns, 4th column is a status column and I wanted to colour cells of this 4th column according to status, so I tried something like:

<DataGrid.CellStyle>
  <Style TargetType="{x:Type DataGridCell}">
    <Setter Property="BorderBrush" Value="#bababa" />
    <Setter Property="BorderThickness" Value="1" />
    <Setter Property="Foreground" Value="White" />
    <Style.Triggers>
       <DataTrigger Binding="{Binding DataCollectionStatus}" Value="{x:Static collectionStatus:ModuleDataCollectionStatus.Collected}">
           <Setter Property="Background" Value="Green" />
       </DataTrigger>
       <DataTrigger Binding="{Binding DataCollectionStatus}" Value="{x:Static collectionStatus:ModuleDataCollectionStatus.Collecting}">
           <Setter Property="Background" Value="Orange" />
       </DataTrigger>
       <DataTrigger Binding="{Binding DataCollectionStatus}" Value="{x:Static collectionStatus:ModuleDataCollectionStatus.NotCollected}">
           <Setter Property="Background" Value="Red" />
       </DataTrigger>
     </Style.Triggers>
  </Style>
</DataGrid.CellStyle>

<DataGrid.Columns>
  <DataGridTextColumn Width="100" Header="Module type" Binding="{Binding ModuleTypeAsString}" />
  <DataGridTextColumn Width="70" Header="Rack ID" Binding="{Binding RackIdAsString}" />
  <DataGridTextColumn Width="70" Header="Slot no" Binding="{Binding ModuleSlotAsString}" />
  <DataGridTextColumn Width="200" Header="Status" Binding="{Binding DataCollectionStatusAsString}" />
</DataGrid.Columns>

Well it partially works as it colours all the cells according to status, I also tried adding Style to DataGridTextColumn but I get message that i can not access those properties.

Can I do colour cells only in 4th column?

Upvotes: 0

Views: 866

Answers (1)

Andy
Andy

Reputation: 12276

As well as on the entire datagrid, there's a cellstyle property you can use on a datagridcolumn. As an example:

    <DataGridTextColumn Binding="{Binding Title}">
         <DataGridTextColumn.CellStyle>
                <Style TargetType="DataGridCell">
                       <Style.Triggers>
                             <Trigger Property="IsSelected" Value="True">
                                    <Setter Property="Background" Value="{Binding bBrush}"/>
                              </Trigger>
                       </Style.Triggers>
                </Style>
         </DataGridTextColumn.CellStyle>
 </DataGridTextColumn>

With complicated logic which is specific to that one place it can be easier to maintain to encapsulate that logic in the row viewmodel and "just" return a brush to bind. The view then doesn't have a dependency on an enum or whatever that is. Some people then argue that it's a view responsibility to decide on presentation. My personal view is that whatever is easier to maintain is best.

Upvotes: 1

Related Questions