AgostinoX
AgostinoX

Reputation: 7683

WPF DataGrid - Apply style to whichever column is displayed as first with DataTrigger

In a DataGrid, I need to apply a style based on a certain condition implemented in my data context. But it has to be applied to the cells of the first column only.

Since a user is allowed to reorder columns, I don't know which is the first one in advance. So I tried to implement it at the CellStyle level, with a condition on the DisplayIndex:

<Condition Binding="{Binding Column.DisplayIndex, RelativeSource={RelativeSource  Mode=FindAncestor, AncestorType={x:Type DataGridCell}}}" Value="0" />

I put it into a MultiDataTrigger with the condition on the data, that is:

<Condition Binding="{Binding IsInEvidence}" Value="False" />

IsInEvidence is a bool property in my row-level view model. If I leave this only, it works fine, but it gets applied to all the cells.

<DataGrid Items={Binding Items}/>
   <DataGrid.CellStyle>
      <Style TargetType="DataGridCell">
         <Style.Triggers>
            <MultiDataTrigger>
               <MultiDataTrigger.Conditions>
                  <Condition Binding="{Binding IsInEvidence}" Value="False" />
                  <Condition Binding="{Binding Column.DisplayIndex, RelativeSource={RelativeSource  Mode=FindAncestor, AncestorType={x:Type DataGridCell}}}" Value="0" />
               </MultiDataTrigger.Conditions>
               <Setter Property="Background" Value="Yellow"/>
            </MultiDataTrigger>
         </Style.Triggers>
      </Style>
   </DataGrid.CellStyle>

   <!-- Column defintions and so on -->

</DataGrid>

Upvotes: 1

Views: 246

Answers (1)

thatguy
thatguy

Reputation: 22079

Change your Condition binding to use RelativeSource={RelativeSource Self}, then it works.

<Condition Binding="{Binding Column.DisplayIndex, RelativeSource={RelativeSource Self}}" Value="0"/>

Upvotes: 1

Related Questions